之前敲代码的时候,避免不了各种try..catch, 如果业务复杂一点, 就会发现全都是try…catch

try{
..........
}catch(Exception1 e){
..........
}catch(Exception2 e){
...........
}catch(Exception3 e){
...........
}

这样其实代码既不简洁好看 ,我们敲着也烦, 一般我们可能想到用拦截器去处理, 但是既然现在Spring这么火,AOP大家也不陌生, 那么Spring一定为我们想好了这个解决办法.果然: @ExceptionHandler

源码

//该注解作用对象为方法
@Target({ElementType.METHOD})
//在运行时有效
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
//value()可以指定异常类
Class<? extends Throwable>[] value() default {};
}

 @ControllerAdvice
源码

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
//bean对象交给spring管理生成
@Component
public @interface ControllerAdvice {
@AliasFor("basePackages")
String[] value() default {};

@AliasFor("value")
String[] basePackages() default {};

Class<?>[] basePackageClasses() default {};

Class<?>[] assignableTypes() default {};

Class<? extends Annotation>[] annotations() default {};
}

从名字上可以看出大体意思是控制器增强

所以结合上面我们可以知道,使用@ExceptionHandler,可以处理异常, 但是仅限于当前Controller中处理异常, @ControllerAdvice可以配置basePackage下的所有controller. 所以结合两者使用,就可以处理全局的异常了.

 1.定义一个异常
public class CustomGenericException extends RuntimeException{
private static final long serialVersionUID = 1L;

private String errCode;
private String errMsg;

public String getErrCode() {
return errCode;
}

public void setErrCode(String errCode) {
this.errCode = errCode;
}

public String getErrMsg() {
return errMsg;
}

public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}

public CustomGenericException(String errCode, String errMsg) {
this.errCode = errCode;
this.errMsg = errMsg;
}
}

2. 定义一个controller
这里我们就不用try catch了, 直接抛异常就可以了

@Controller
@RequestMapping("/exception")
public class ExceptionController {

@RequestMapping(value = "/{type}", method = RequestMethod.GET)
public ModelAndView getPages(@PathVariable(value = "type") String type) throws Exception{
if ("error".equals(type)) {
// 由handleCustomException处理
throw new CustomGenericException("E888", "This is custom message");
} else if ("io-error".equals(type)) {
// 由handleAllException处理
throw new IOException();
} else {
return new ModelAndView("index").addObject("msg", type);
}
}
}

3.异常处理类
这个类就可以当做controller类写了, 返回参数跟mvc返回参数一样

@ControllerAdvice
public class ExceptionsHandler {

@ExceptionHandler(CustomGenericException.class)//可以直接写@ExceptionHandler,不指明异常类,会自动映射
public ModelAndView customGenericExceptionHnadler(CustomGenericException exception){ //还可以声明接收其他任意参数
ModelAndView modelAndView = new ModelAndView("generic_error");
modelAndView.addObject("errCode",exception.getErrCode());
modelAndView.addObject("errMsg",exception.getErrMsg());
return modelAndView;
}

//可以通过ResponseStatus配置返回的状态码
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)//可以直接写@EceptionHandler,IOExeption继承于Exception
public ModelAndView allExceptionHandler(Exception exception){
ModelAndView modelAndView = new ModelAndView("generic_error");
modelAndView.addObject("errMsg", "this is Exception.class");
return modelAndView;
}
}

4.jsp页面
正常的页面

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h2>Spring MVC @ExceptionHandler Example</h2>

<c:if test="${not empty msg}">
<h2>${msg}</h2>
</c:if>

</body>
</html>

异常处理页面

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>

<c:if test="${not empty errCode}">
<h1>${errCode} : System Errors</h1>
</c:if>

<c:if test="${empty errCode}">
<h1>System Errors</h1>
</c:if>

<c:if test="${not empty errMsg}">
<h2>${errMsg}</h2>
</c:if>

</body>
</html>

Spring的@ExceptionHandler和@ControllerAdvice统一处理异常的更多相关文章

  1. @ExceptionHandler和@ControllerAdvice统一处理异常

    //@ExceptionHandler和@ControllerAdvice统一处理异常//统一处理异常的controller需要放在和普通controller同级的包下,或者在ComponentSca ...

  2. @ControllerAdvice与@ControllerAdvice统一处理异常

    https://blog.csdn.net/zzzgd_666/article/details/81544098(copy) 详细看此 所以结合上面我们可以知道,使用@ExceptionHandler ...

  3. Spring异常处理@ExceptionHandler

    最近学习Spring时,认识到Spring异常处理的强大.之前处理工程异常,代码中最常见的就是try-catch-finally,有时一个try,多个catch,覆盖了核心业务逻辑: try{ ... ...

  4. spring boot:使接口返回统一的RESTful格式数据(spring boot 2.3.1)

    一,为什么要使用REST? 1,什么是REST? REST是软件架构的规范体系,它把资源的状态用URL进行资源定位, 以HTTP动作(GET/POST/DELETE/PUT)描述操作 2,REST的优 ...

  5. 【统一异常处理】@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常

    1.利用springmvc注解对Controller层异常全局处理 对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service ...

  6. @ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常==》记录

    对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚. 如此一来, ...

  7. 转:@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常

    继承 ResponseEntityExceptionHandler 类来实现针对 Rest 接口 的全局异常捕获,并且可以返回自定义格式: 复制代码 1 @Slf4j 2 @ControllerAdv ...

  8. 只需一步,在Spring Boot中统一Restful API返回值格式与统一处理异常

    ## 统一返回值 在前后端分离大行其道的今天,有一个统一的返回值格式不仅能使我们的接口看起来更漂亮,而且还可以使前端可以统一处理很多东西,避免很多问题的产生. 比较通用的返回值格式如下: ```jav ...

  9. Spring Cloud实战 | 第九篇:Spring Cloud整合Spring Security OAuth2认证服务器统一认证自定义异常处理

    本文完整代码下载点击 一. 前言 相信了解过我或者看过我之前的系列文章应该多少知道点我写这些文章包括创建 有来商城youlai-mall 这个项目的目的,想给那些真的想提升自己或者迷茫的人(包括自己- ...

随机推荐

  1. 使用CIFAR-10样本数据集测试卷积神经网络(ConvolutionalNeuralNetwork,CNN)

    第一次将例程跑起来了,有些兴趣. 参考的是如下URL: http://www.yidianzixun.com/article/0KNz7OX1 本来是比较Keras和Tensorflow的,我现在的水 ...

  2. 「TJOI2018」str

    碱基序列 题目描述 小豆参加了生物实验室.在实验室里,他主要研究蛋白质.他现在研究的蛋白质是由$k$个氨基酸按一定顺序构成的.每一个氨基酸都可能有$a$种碱基序列$s_{i,j}$构成. 现在小豆有一 ...

  3. 快速IO

    namespace IO { #define gc() (iS==iT?(iT=(iS=ibuff)+fread(ibuff,1,SIZ,stdin),(iS==iT?EOF:iS++)):iS++) ...

  4. XStream 1.4.10版本处理xml使用问题

    XStream pom依赖: <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifa ...

  5. asp.net大文件分块上传断点续传demo

    IE的自带下载功能中没有断点续传功能,要实现断点续传功能,需要用到HTTP协议中鲜为人知的几个响应头和请求头. 一. 两个必要响应头Accept-Ranges.ETag 客户端每次提交下载请求时,服务 ...

  6. 2017.10.5 国庆清北 D5T2 整除

    80分暴力 /*找规律80分TLE俩点 忘了啥规律了. */ #include<iostream> #include<cstdio> #include<cmath> ...

  7. BZOJ 1073: [SCOI2007]kshort

    二次联通门 : BZOJ 1073: [SCOI2007]kshort /* BZOJ 1073: [SCOI2007]kshort A* k短路 但是会爆一个点, 是卡A*的 */ #include ...

  8. Redash(开源轻量级商业智能) 生产环境部署及实践 (without docker)

    一直在调研一个轻量级开源的 BI 系统.之前我们生产环境使用的 aliyun 的 QuickBi,也调研了另外一个 airflow 的开源商业智能 superset.不得不承认 QuickBI 正在日 ...

  9. SpringData 简单的条件查询

    今天在写springdata条件查询时,JpaRepository的findOne方法,不知道是因为版本的原因还是其他原因,总是查询不出来数据 //springdata jpa版本为1.5.15,配置 ...

  10. LAMP企业架构读写分离

    1.1  LAMP企业架构读写分离 LAMP+Discuz+Redis缓解了MYSQL的部分压力,但是如果访问量非常大,Redis缓存中第一次没有缓存数据,会导致MYSQL数据库压力增大,此时可以基于 ...