SpringMVC异常处理注解@ExceptionHandler@ControllerAdvice@ResponseStatus
参考:
http://blog.csdn.net/w372426096/article/details/78429132
http://blog.csdn.net/w372426096/article/details/78429141
@ExceptionHandler:统一处理某一类异常,从而能够减少代码重复率和复杂度
源码如下:

1 @Target({ElementType.METHOD})
2 @Retention(RetentionPolicy.RUNTIME)
3 @Documented
4 public @interface ExceptionHandler {
5 Class<? extends Throwable>[] value() default {};
6 }

注解作用对象为方法,并且在运行时有效,value()可以指定异常类。由该注解注释的方法可以具有灵活的输入参数(详细参见Spring API):
- 异常参数:包括一般的异常或特定的异常(即自定义异常),如果注解没有指定异常类,会默认进行映射。
- 请求或响应对象 (Servlet API or Portlet API): 你可以选择不同的类型,如ServletRequest/HttpServletRequest或PortleRequest/ActionRequest/RenderRequest
。 - Session对象(Servlet API or Portlet API): HttpSession或PortletSession。
- WebRequest或NativeWebRequest
- Locale
- InputStream/Reader
- OutputStream/Writer
Model
方法返回值可以为:
- ModelAndView对象
- Model对象
- Map对象
- View对象
- String对象
- 还有@ResponseBody、HttpEntity<?>或ResponseEntity<?>,以及void
@ControllerAdvice
源码如下:

1 @Target({ElementType.TYPE})
2 @Retention(RetentionPolicy.RUNTIME)
3 @Documented
4 @Component
5 public @interface ControllerAdvice {
6 @AliasFor("basePackages")
7 String[] value() default {};
8
9 @AliasFor("value")
10 String[] basePackages() default {};
11
12 Class<?>[] basePackageClasses() default {};
13
14 Class<?>[] assignableTypes() default {};
15
16 Class<? extends Annotation>[] annotations() default {};
17 }

该注解作用对象为TYPE,包括类、接口和枚举等,在运行时有效,并且可以通过Spring扫描为bean组件。其可以包含由@ExceptionHandler、@InitBinder 和@ModelAttribute标注的方法,可以处理多个Controller类,这样所有控制器的异常可以在一个地方进行处理
@ResponseStatus:可以将某种异常映射为HTTP状态码
无论是普通的WEB项目,还是用SpringMVC实现的restful服务,都曾经历过下面两个问题:
- @PostMapping(path = "/selectByAcctcode")
- public MerAccountQueryResponse selectByAcctcode(@Valid @RequestBody MerAccountQueryRequest request,BindingResult result) {
- log.info(Constants.REQUEST_MSG, JSON.toJSONString(request));
- MerAccountQueryResponse response = new MerAccountQueryResponse();
- try {
- Pageable pageable = new PageRequest(request.getPageNum(), request.getPageSize());
- response = merAccountService.selectByAcctcode(request, pageable);
- // 返回成功报文
- MessageUtil.createCommMsg(response);
- } catch (BizException e) {
- log.error(Constants.BUSINESS_ERROR, e);
- // 组织错误报文
- MessageUtil.errRetrunInAction(response, e);
- } catch (Exception ex) {
- log.error(Constants.EXCEPTION_ERROR, ex);
- // 组织错误报文
- MessageUtil.createErrorMsg(response,ex);
- }
- log.info(Constants.REPONSE_MSG, JSON.toJSONString(response));
- return response;
- }
当你有100个接口的时候,就得重复100次,如果你觉得代码量也就那么点,copy就copy吧,反正我是代码的搬运工,只是你有曾想过我可以抽取出来吗?
我们在写Controller的时候,如果没有出现过异常固然没问题,但一旦出现异常了,如果你处理了,那就需要你手动指定跳转到事先定义好的界面,如果你没处理,那将得到是一个非常丑陋的界面,如下:
如何避免这种问题呢???
- @Controller
- @RequestMapping(value = "exception")
- public class ExceptionHandlerController {
- @ExceptionHandler({ ArithmeticException.class })
- public String handleArithmeticException(Exception e) {
- e.printStackTrace();
- return "error";
- }
- @RequestMapping(value = "e/{id}", method = { RequestMethod.GET })
- @ResponseBody
- public String testExceptionHandle(@PathVariable(value = "id") Integer id) {
- System.out.println(10 / id);
- return id.toString();
- }
- }
当访问exception/e/0的时候,会抛出ArithmeticException异常,@ExceptionHandler就会处理并响应error.jsp
- @Controller
- @RequestMapping(value = "exception")
- public class ExceptionHandlerController {
- @ExceptionHandler({ ArithmeticException.class })
- @ResponseBody
- public String handleArithmeticException(Exception e) {
- e.printStackTrace();
- JSONObject jo = new JSONObject();
- jo.put("resCode","999999");
- jo.put("resMsg","系统异常");
- return jo.toString();
- }
- @RequestMapping(value = "e/{id}", method = { RequestMethod.GET })
- @ResponseBody
- public String testExceptionHandle(@PathVariable(value = "id") Integer id) {
- System.out.println(10 / id);
- return id.toString();
- }
- }
当然实际项目中,并不会像我这里写的这么简陋,我这里只是抛砖引玉,给你一个思路。
在实际项目中,可能碰到这种情况,我们提供的服务,调用方并不需要json报文中的消息,调用方只关注响应码,比如200,代表调用正常;404,代表请求资源不存在;502,代表系统异常。。。等等。我们又该如何去做?
- package com.somnus.exception;
- import org.springframework.http.HttpStatus;
- import org.springframework.web.bind.annotation.ResponseStatus;
- @ResponseStatus(value=HttpStatus.BAD_GATEWAY)
- public class HttpStatusException extends RuntimeException {
- private static final long serialVersionUID = 1L;
- public HttpStatusException() {
- super();
- }
- public HttpStatusException(String message, Throwable cause) {
- super(message, cause);
- }
- public HttpStatusException(String message) {
- super(message);
- }
- public HttpStatusException(Throwable cause) {
- super(cause);
- }
- }
- @Controller
- @RequestMapping(value = "status")
- public class ResponseStatusController {
- @RequestMapping(value = "e/{id}", method = { RequestMethod.GET })
- @ResponseBody
- public String status(@PathVariable(value = "id") Integer id){
- if(id % 2 != 0){
- throw new HttpStatusException();
- }
- return id.toString();
- }
- }
效果如下:
另外这里不得不提一点需要注意的,不要轻易把@ResponseStatus修饰目标方法,因为无论它执行方法过程中有没有异常产生,用户都会得到异常的界面,而目标方法正常执行。
- package com.somnus.controller;
- import org.springframework.http.HttpStatus;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.ResponseStatus;
- import com.somnus.exception.HttpStatusException;
- @Controller
- @RequestMapping(value = "status")
- public class ResponseStatusController {
- /**
- * ResponseStatus修饰目标方法,无论它执行方法过程中有没有异常产生,用户都会得到异常的界面。而目标方法正常执行
- * @param id
- * @return
- */
- @RequestMapping(value = "e2/{id}", method = { RequestMethod.GET })
- @ResponseStatus(value=HttpStatus.BAD_GATEWAY)
- @ResponseBody
- public String status2(@PathVariable(value = "id") Integer id){
- System.out.println(10 / id);
- return id.toString();
- }
- }
可以看到哪怕是响应2了,但是响应码其实还是502
如果我们要给jdk自带的异常提供一个响应码呢,我们又不可能去改源码,这时候@ResponseStatus就得配和@ControllerAdvice一起使用了,如下:
- @Controller
- @RequestMapping(value = "exception")
- public class ExceptionHandlerController {
- @ExceptionHandler({ NullPointerException.class })
- @ResponseStatus(value=HttpStatus.NOT_FOUND)
- public void handleNullPointerException(Exception e) {
- e.printStackTrace();
- }
- @RequestMapping(value = "e3/{id}", method = { RequestMethod.GET })
- @ResponseBody
- public String testExceptionHandle3(@PathVariable(value = "id") Integer id) {
- List<String> list = 4 % id == 0 ? null : Arrays.asList(new String[]{"a","b","c","d"});
- return list.get(id);
- }
- }
当我们抛出NullPointerException异常的时候会发生什么呢
当一个Controller中有多个@ExceptionHandler注解出现时,那么异常被哪个方法捕捉呢?这就存在一个优先级的问题,@ExceptionHandler的优先级是:在异常的体系结构中,哪个异常与目标方法抛出的异常血缘关系越紧密,就会被哪个捕捉到
@ExceptionHandler这个只会是在当前的Controller里面起作用,如果想在所有的Controller里面统一处理异常的话,可以用@ControllerAdvice来创建一个专门处理的类,我们在下一篇做介绍。
@ControllerAdvice,是Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强。让我们先看看@ControllerAdvice的实现:
- package org.springframework.web.bind.annotation;
- @Target(ElementType.TYPE)
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @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 {};
没什么特别之处,该注解使用@Component注解,这样的话当我们使用<context:component-scan>扫描时也能扫描到。
再一起看看官方提供的comment。
大致意思是:
@ControllerAdvice是一个@Component,用于定义@ExceptionHandler,@InitBinder和@ModelAttribute方法,适用于所有使用@RequestMapping方法。Spring4之前,
@ControllerAdvice在同一调度的Servlet中协助所有控制器。Spring4已经改变:@ControllerAdvice支持配置控制器的子集,而默认的行为仍然可以利用。在Spring4中,
@ControllerAdvice通过annotations(),basePackageClasses(),basePackages()方法定制用于选择控制器子集。
不过据经验之谈,只有配合@ExceptionHandler最有用,其它两个不常用。
在SpringMVC重要注解(一)@ExceptionHandler和@ResponseStatus我们提到,如果单使用@ExceptionHandler,只能在当前Controller中处理异常。但当配合@ControllerAdvice一起使用的时候,就可以摆脱那个限制了。
- package com.somnus.advice;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.ResponseBody;
- @ControllerAdvice
- public class ExceptionAdvice {
- @ExceptionHandler({ ArrayIndexOutOfBoundsException.class })
- @ResponseBody
- public String handleArrayIndexOutOfBoundsException(Exception e) {
- e.printStackTrace();
- return "testArrayIndexOutOfBoundsException";
- }
- }
- @Controller
- @RequestMapping(value = "exception")
- public class ExceptionHandlerController {
- @RequestMapping(value = "e2/{id}", method = { RequestMethod.GET })
- @ResponseBody
- public String testExceptionHandle2(@PathVariable(value = "id") Integer id) {
- List<String> list = Arrays.asList(new String[]{"a","b","c","d"});
- return list.get(id-1);
- }
- }
当我们访问http://localhost:8080/SpringMVC/exception/e2/5的时候会抛出ArrayIndexOutOfBoundsException异常,这时候定义在@ControllerAdvice中的@ExceptionHandler就开始发挥作用了。
如果我们想定义一个处理全局的异常
- package com.somnus.advice;
- import javax.servlet.http.HttpServletRequest;
- import org.springframework.core.annotation.AnnotationUtils;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.ResponseStatus;
- @ControllerAdvice
- public class ExceptionAdvice {
- @ExceptionHandler({ Exception.class })
- @ResponseBody
- public String handException(HttpServletRequest request ,Exception e) throws Exception {
- e.printStackTrace();
- return e.getMessage();
- }
- }
乍一眼看上去毫无问题,但这里有一个纰漏,由于Exception是异常的父类,如果你的项目中出现过在自定义异常中使用@ResponseStatus的情况,你的初衷是碰到那个自定义异常响应对应的状态码,而这个控制器增强处理类,会首先进入,并直接返回,不会再有@ResponseStatus的事情了,这里为了解决这种纰漏,我提供了一种解决方式。
- package com.somnus.advice;
- import javax.servlet.http.HttpServletRequest;
- import org.springframework.core.annotation.AnnotationUtils;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.ResponseStatus;
- @ControllerAdvice
- public class ExceptionAdvice {
- @ExceptionHandler({ Exception.class })
- @ResponseBody
- public String handException(HttpServletRequest request ,Exception e) throws Exception {
- e.printStackTrace();
- //If the exception is annotated with @ResponseStatus rethrow it and let
- // the framework handle it - like the OrderNotFoundException example
- // at the start of this post.
- // AnnotationUtils is a Spring Framework utility class.
- if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
- throw e;
- }
- // Otherwise setup and send the user to a default error-view.
- /*ModelAndView mav = new ModelAndView();
- mav.addObject("exception", e);
- mav.addObject("url", request.getRequestURL());
- mav.setViewName(DEFAULT_ERROR_VIEW);
- return mav;*/
- return e.getMessage();
- }
- }
如果碰到了某个自定义异常加上了@ResponseStatus,就继续抛出,这样就不会让自定义异常失去加上@ResponseStatus的初衷。
SpringMVC异常处理注解@ExceptionHandler@ControllerAdvice@ResponseStatus的更多相关文章
- springBoot注解大全JPA注解springMVC相关注解全局异常处理
https://www.cnblogs.com/tanwei81/p/6814022.html 一.注解(annotations)列表 @SpringBootApplication:包含了@Compo ...
- SpringMVC重要注解 @ControllerAdvice
@ControllerAdvice,是Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强.让我们先看看@ControllerAdvice的实现: package org.spring ...
- Spring中通过java的@Valid注解和@ControllerAdvice实现全局异常处理。
通过java原生的@Valid注解和spring的@ControllerAdvice和@ExceptionHandler实现全局异常处理的方法: controller中加入@Valid注解: @Req ...
- SpringMVC异常处理机制详解[附带源码分析]
目录 前言 重要接口和类介绍 HandlerExceptionResolver接口 AbstractHandlerExceptionResolver抽象类 AbstractHandlerMethodE ...
- SpringMVC异常处理机制
SpringMVC异常处理机制 springMVC会将所有在doDispatch方法中的异常捕获,然后处理.无法处理的异常会抛出给容器处理. 在doDispatch()中调用processDispat ...
- SpringMVC常用注解(三)
一.@Controller .@RestController 和 @ControllerAdvice 1. @Controller @Controller 用于标记在一个类上,使用它标记的类就是一个S ...
- springmvc异常处理解析#ExceptionHandlerExceptionResolver
开头 试想一下我们一般怎么统一处理异常呢,答:切面.但抛开切面不讲,如果对每一个controller方法抛出的异常做专门处理,那么着实太费劲了,有没有更好的方法呢?当然有,就是本篇文章接下来要介绍的s ...
- SpringMVC异常处理方式
一.描述 在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的.不可预知的异常需要处理.每个过程都单独处理异常,系统的代码耦合 ...
- Spring 和 SpringMVC 常用注解和配置(@Autowired、@Resource、@Component、@Repository、@Service、@Controller的区别)
Spring 常用注解 总结内容 一.Spring部分 1.声明bean的注解 2.注入bean的注解 3.java配置类相关注解 4.切面(AOP)相关注解 5.事务注解 6.@Bean的属性支持 ...
随机推荐
- Mongodb 备份 数据导出导入
MongoDB 客户端工具 mongochef 可以进行一系类操作 MongoDB 非客户端操作 : mongod 备份导出 mongoexport -h IP --port 端口 -u 用户名 -p ...
- Fragment中onCreateView()和onActivityCreated():静态/动态View
在编写Fragment时,在onCreateView()方法中启动了一个初始化自定义View的方法 initView(),但是调试时就崩溃,打印日志发现是这里出了问题,就将这个方法放到了onActiv ...
- Pytorch 各种奇葩古怪的使用方法
h1 { counter-reset: h2counter; } h2 { counter-reset: h3counter; } h3 { counter-reset: h4counter; } h ...
- C语言拼接字符串 -- 使用strcat()函数
[头文件]#include <string.h> [原型] char *strcat(char *dest, const char *src); [参数]: dest 为目标字符串指针,s ...
- SpringBoot整合Email(电子邮件服务)
(1).导入starter依赖 <dependency> <groupId>org.springframework.boot</groupId> <artif ...
- GCC的符号可见性——解决多个库同名符号冲突问题
引用自:https://github.com/wwbmmm/blog/wiki/gcc_visibility 问题 最近项目遇到一些问题,场景如下 主程序依赖了两个库libA的funcA函数和libB ...
- Android手机刘海屏(附工具类)
工具类 根据VIVO.OPPO.华为官方文档,这里整理了一个刘海屏工具类,判断设备是否为刘海屏,其他厂商公布相关方法后也会在此更新. OPPO: /** * OPPO * * @param conte ...
- ThreadLocal和线程同步机制对比
共同点: ThreadLocal和线程同步机制都是为了解决多线程中相同变量的访问冲突问题. 区别: 在同步机制中,通过对象的锁机制保证同一时间只有一个线程访问变量. 这时该变量是多个线程共享的,使用同 ...
- vuejs之v-if-ajax异步请求数据遇到的坑
场景: params是异步请求获得的数据是一个对象,对象中又有chefHealthInfos数组 渲染时候会报错: 分析: 这是因为可以把v-if看成渲染了两次,两次结果params分别为{},{ch ...
- [工具/PC]计算机中丢失libiconv-2.dll,丢失libintl-8.dll,无法定位程序输入点libiconv于动态链接库libiconv-2.dll上问题解决方法
CodeBlocks 1. 背景,为了学习C语言,在win系统上下载了codeBlock,先简单介绍下:Code::Blocks 是一个开放源码的全功能的跨平台C/C++集成开发环境. Code::B ...