之前敲代码的时候,避免不了各种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. 访问stackoverflow非常慢

    其实GFW并没有限制访问stackoverflow,但是打开stackoverflow会非常慢. 解决方法是 打开host文件加入下面这句  127.0.0.1 ajax.googleapis.com ...

  2. JDK源码那些事儿之ConcurrentLinkedDeque

    非阻塞队列ConcurrentLinkedQueue我们已经了解过了,既然是Queue,那么是否有其双端队列实现呢?答案是肯定的,今天就继续说一说非阻塞双端队列实现ConcurrentLinkedDe ...

  3. destoon二次开发-用户名、邮箱、手机账号中间字符串以*隐藏 扩展

    因为dt里面有用户名.邮箱.手机账号等,所以想办法进行隐藏保护用户隐私,所以个人就试着写了这个代码. 在api/extend.func.php文件下增加以下代码: //用户名.邮箱.手机账号中间字符串 ...

  4. matlab运行程序时出现failed to start a parallel pool

    运行matlab做并行时得到如下报错: failed to start a parallel pool. (For information in addition to the causing err ...

  5. MCMC蒙特卡罗马尔科夫模型

    https://www.cnblogs.com/pinard/p/6645766.html https://blog.csdn.net/saltriver/article/details/521949 ...

  6. webuploader+php如何实现分片+断点续传

    这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...

  7. Intel 80286 CPU

    一.80286概述 INTEL 1982年推出80286芯片,该芯片相比8086和8088有了飞跃式发展,虽然它仍是16位结构,但在CPU内部含有13.4万个晶体管,时钟频率由最初6MHz逐步提高到2 ...

  8. COGS 2687 讨厌整除的小明

    二次联通门 : COGS 2687 讨厌整除的小明 /* cogs 2687 讨厌整除的小明 打表出奇迹.. 考场时看了一下样例就感觉有非常鬼畜的做法.. 手搞几组数据做法就出来了... 2333 * ...

  9. 洛谷P1199三国游戏

    题目 博弈论+贪心. 由于我们是先手,所以我们其实是必赢的,而且其实选完前两次,就已经结束了,因为接下来选的每一次其实都没有我们前几次选的好.而且又因为机器人会把我们想选的最好的拿走,那我们就只能拿走 ...

  10. Python 全栈开发【第0篇】:目录

    Python 全栈开发[第0篇]:目录   第一阶段:Python 开发入门 Python 全栈开发[第一篇]:计算机原理&Linux系统入门 Python 全栈开发[第二篇]:Python基 ...