SpringMVC全局异常处理

【SpringMVC学习07】SpringMVC中的统一异常处理

我们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。在开发中,不管是dao层、service层还是controller层,都有可能抛出异常,在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护。这篇博文主要总结一下SpringMVC中如何统一处理异常。

1. 异常处理思路

  首先来看一下在springmvc中,异常处理的思路(我已尽力画好看点了,不要喷我~): 
springmvc异常处理 
  如上图所示,系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。明白了springmvc中的异常处理机制,下面就开始分析springmvc中的异常处理。

2. springmvc中自带的简单异常处理器

  springmvc中自带了一个异常处理器叫SimpleMappingExceptionResolver,该处理器实现了HandlerExceptionResolver 接口,全局异常处理器都需要实现该接口。我们要使用这个自带的异常处理器,首先得在springmvc.xml文件中配置该处理器:

 

复制代码
<!-- springmvc提供的简单异常处理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
     <!-- 定义默认的异常处理页面 -->
    <property name="defaultErrorView" value="/WEB-INF/jsp/error.jsp"/>
    <!-- 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception --> 
    <property name="exceptionAttribute" value="ex"/>
    <!-- 定义需要特殊处理的异常,这是重要点 --> 
    <property name="exceptionMappings">
        <props>
            <prop key="ssm.exception.CustomException">/WEB-INF/jsp/custom_error.jsp</prop>
        </props>
        <!-- 还可以定义其他的自定义异常 -->
    </property>
</bean>
复制代码

 

从上面的配置来看,最重要的是要配置特殊处理的异常,这些异常一般都是我们自定义的,根据实际情况来自定义的异常,然后也会跳转到不同的错误显示页面显示不同的错误信息。这里就用一个自定义异常CustomException来说明问题,定义如下:

复制代码
//定义一个简单的异常类
public class CustomException extends Exception {

    //异常信息
    public String message;

    public CustomException(String message) {
        super(message);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}
复制代码

接下来就是写测试程序了,还是使用查询的例子,如下: 
异常 
  然后我们在前台输入url来测试:http://localhost:8080/SpringMVC_Study/editItems.action?id=11,故意传一个id为11,我的数据库中没有id为11的项,所以肯定查不到,反正让它查不到即可。这样它就会抛出自定义的异常,然后被上面配置的全局异常处理器捕获并执行,跳转到我们指定的页面,然后显示一下该商品不存在即可。所以这个流程是很清晰的。 
  从上面的过程可知,使用SimpleMappingExceptionResolver进行异常处理,具有集成简单、有良好的扩展性(可以任意增加自定义的异常和异常显示页面)、对已有代码没有入侵性等优点,但该方法仅能获取到异常信息,若在出现异常时,对需要获取除异常以外的数据的情况不适用。

 

3. 自定义全局异常处理器

 

  全局异常处理器处理思路:

 

  1. 解析出异常类型
  2. 如果该异常类型是系统自定义的异常,直接取出异常信息,在错误页面展示
  3. 如果该异常类型不是系统自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)

springmvc提供一个HandlerExceptionResolver接口,自定义全局异常处理器必须要实现这个接口,如下:

 

复制代码
public class CustomExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {

        ex.printStackTrace();
        CustomException customException = null;

        //如果抛出的是系统自定义的异常则直接转换
        if(ex instanceof CustomException) {
            customException = (CustomException) ex;
        } else {
            //如果抛出的不是系统自定义的异常则重新构造一个未知错误异常
            //这里我就也有CustomException省事了,实际中应该要再定义一个新的异常
            customException = new CustomException("系统未知错误");
        }

        //向前台返回错误信息
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", customException.getMessage());
        modelAndView.setViewName("/WEB-INF/jsp/error.jsp");

        return modelAndView;
    }
}
复制代码

 

全局异常处理器中的逻辑很清楚,我就不再多说了,然后就是在springmvc.xml中配置这个自定义的异常处理器:

<!-- 自定义的全局异常处理器 
只要实现HandlerExceptionResolver接口就是全局异常处理器-->
<bean class="ssm.exception.CustomExceptionResolver"></bean> 

然后就可以使用上面那个测试用例再次测试了。可以看出在自定义的异常处理器中能获取导致出现异常的对象,有利于提供更详细的异常处理信息。一般用这种自定义的全局异常处理器比较多。

4. @ExceptionHandler注解实现异常处理

  还有一种是使用注解的方法,我大概说一下思路,因为这种方法对代码的入侵性比较大,我不太喜欢用这种方法。 
  首先写个BaseController类,并在类中使用@ExceptionHandler注解声明异常处理的方法,如:

 

复制代码
public class BaseController { 
    @ExceptionHandler  
    public String exp(HttpServletRequest request, Exception ex) { 
    //异常处理
    //......
    }
}
复制代码

 

然后将所有需要异常处理的Controller都继承这个BaseController,虽然从执行来看,不需要配置什么东西,但是代码有侵入性,需要异常处理的Controller都要继承它才行。 
  关于springmvc的异常处理,就总结这么多吧。 

 

早年同窗始相知,三载瞬逝情却萌。年少不知愁滋味,犹读红豆生南国。别离方知相思苦,心田红豆根以生。
 

Spring MVC异常统一处理的三种方式

 

正文

Spring 统一异常处理有 3 种方式,分别为:

  1. 使用 @ ExceptionHandler 注解
  2. 实现 HandlerExceptionResolver 接口
  3. 使用 @controlleradvice 注解

使用 @ ExceptionHandler 注解

使用该注解有一个不好的地方就是:进行异常处理的方法必须与出错的方法在同一个Controller里面。使用如下:

复制代码
 1 @Controller      
 2 public class GlobalController {               
 3 
 4    /**    
 5      * 用于处理异常的    
 6      * @return    
 7      */      
 8     @ExceptionHandler({MyException.class})       
 9     public String exception(MyException e) {       
10         System.out.println(e.getMessage());       
11         e.printStackTrace();       
12         return "exception";       
13     }       
14 
15     @RequestMapping("test")       
16     public void test() {       
17         throw new MyException("出错了!");       
18     }                    
19 }     
复制代码

可以看到,这种方式最大的缺陷就是不能全局控制异常。每个类都要写一遍。

实现 HandlerExceptionResolver 接口

这种方式可以进行全局的异常控制。例如:

复制代码
 1 @Component  
 2 public class ExceptionTest implements HandlerExceptionResolver{  
 3 
 4     /**  
 5      * TODO 简单描述该方法的实现功能(可选).  
 6      * @see org.springframework.web.servlet.HandlerExceptionResolver#resolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)  
 7      */   
 8     public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,  
 9             Exception ex) {  
10         System.out.println("This is exception handler method!");  
11         return null;  
12     }  
13 }   
复制代码

使用 @ControllerAdvice+ @ ExceptionHandler 注解

上文说到 @ ExceptionHandler 需要进行异常处理的方法必须与出错的方法在同一个Controller里面。那么当代码加入了 @ControllerAdvice,则不需要必须在同一个 controller 中了。这也是 Spring 3.2 带来的新特性。从名字上可以看出大体意思是控制器增强。 也就是说,@controlleradvice + @ ExceptionHandler 也可以实现全局的异常捕捉。

请确保此WebExceptionHandle 类能被扫描到并装载进 Spring 容器中。

复制代码
 1 @ControllerAdvice
 2 @ResponseBody
 3 public class WebExceptionHandle {
 4     private static Logger logger = LoggerFactory.getLogger(WebExceptionHandle.class);
 5     /**
 6      * 400 - Bad Request
 7      */
 8     @ResponseStatus(HttpStatus.BAD_REQUEST)
 9     @ExceptionHandler(HttpMessageNotReadableException.class)
10     public ServiceResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
11         logger.error("参数解析失败", e);
12         return ServiceResponseHandle.failed("could_not_read_json");
13     }
14     
15     /**
16      * 405 - Method Not Allowed
17      */
18     @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
19     @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
20     public ServiceResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
21         logger.error("不支持当前请求方法", e);
22         return ServiceResponseHandle.failed("request_method_not_supported");
23     }
24 
25     /**
26      * 415 - Unsupported Media Type
27      */
28     @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
29     @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
30     public ServiceResponse handleHttpMediaTypeNotSupportedException(Exception e) {
31         logger.error("不支持当前媒体类型", e);
32         return ServiceResponseHandle.failed("content_type_not_supported");
33     }
34 
35     /**
36      * 500 - Internal Server Error
37      */
38     @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
39     @ExceptionHandler(Exception.class)
40     public ServiceResponse handleException(Exception e) {
41         if (e instanceof BusinessException){
42             return ServiceResponseHandle.failed("BUSINESS_ERROR", e.getMessage());
43         }
44         
45         logger.error("服务运行异常", e);
46         e.printStackTrace();
47         return ServiceResponseHandle.failed("server_error");
48     }
49 } 
复制代码

如果 @ExceptionHandler 注解中未声明要处理的异常类型,则默认为参数列表中的异常类型。所以还可以写成这样:

复制代码
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler()
    @ResponseBody
    String handleException(Exception e){
        return "Exception Deal! " + e.getMessage();
    }
}
复制代码

 

参数对象就是 Controller 层抛出的异常对象!

 

继承 ResponseEntityExceptionHandler 类来实现针对 Rest 接口 的全局异常捕获,并且可以返回自定义格式:

复制代码
 1 @Slf4j
 2 @ControllerAdvice
 3 public class ExceptionHandlerBean  extends ResponseEntityExceptionHandler {
 4 
 5     /**
 6      * 数据找不到异常
 7      * @param ex
 8      * @param request
 9      * @return
10      * @throws IOException
11      */
12     @ExceptionHandler({DataNotFoundException.class})
13     public ResponseEntity<Object> handleDataNotFoundException(RuntimeException ex, WebRequest request) throws IOException {
14         return getResponseEntity(ex,request,ReturnStatusCode.DataNotFoundException);
15     }
16 
17     /**
18      * 根据各种异常构建 ResponseEntity 实体. 服务于以上各种异常
19      * @param ex
20      * @param request
21      * @param specificException
22      * @return
23      */
24     private ResponseEntity<Object> getResponseEntity(RuntimeException ex, WebRequest request, ReturnStatusCode specificException) {
25 
26         ReturnTemplate returnTemplate = new ReturnTemplate();
27         returnTemplate.setStatusCode(specificException);
28         returnTemplate.setErrorMsg(ex.getMessage());
29 
30         return handleExceptionInternal(ex, returnTemplate,
31                 new HttpHeaders(), HttpStatus.OK, request);
32     }
33 
34 } 
复制代码

以上就是 Spring 处理程序统一异常的三种方式。

 

@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常

 

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

 

如此一来,我们的 Controller 层就不得不进行 try-catch Service 层的异常,否则会返回一些不友好的错误信息到客户端。但是,Controller 层每个方法体都写一些模板化的 try-catch 的代码,很难看也难维护,特别是还需要对 Service 层的不同异常进行不同处理的时候。例如以下 Controller 方法代码(非常难看且冗余):

 

/**
* 手动处理 Service 层异常和数据校验异常的示例
* @param dog
* @param errors
* @return
*/
@PostMapping(value = "")
AppResponse add(@Validated(Add.class) @RequestBody Dog dog, Errors errors){
AppResponse resp = new AppResponse();
try {
// 数据校验
BSUtil.controllerValidate(errors);

 

// 执行业务
Dog newDog = dogService.save(dog);

 

// 返回数据
resp.setData(newDog);

 

}catch (BusinessException e){
LOGGER.error(e.getMessage(), e);
resp.setFail(e.getMessage());
}catch (Exception e){
LOGGER.error(e.getMessage(), e);
resp.setFail("操作失败!");
}
return resp;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
本文讲解使用 @ControllerAdvice + @ExceptionHandler 进行全局的 Controller 层异常处理,只要设计得当,就再也不用在 Controller 层进行 try-catch 了!而且,@Validated 校验器注解的异常,也可以一起处理,无需手动判断绑定校验结果 BindingResult/Errors 了!

 

一、优缺点
优点:将 Controller 层的异常和数据校验的异常进行统一处理,减少模板代码,减少编码量,提升扩展性和可维护性。
缺点:只能处理 Controller 层未捕获(往外抛)的异常,对于 Interceptor(拦截器)层的异常,Spring 框架层的异常,就无能为力了。
二、基本使用示例
2.1 @ControllerAdvice 注解定义全局异常处理类
@ControllerAdvice
public class GlobalExceptionHandler {
}
1
2
3
请确保此 GlobalExceptionHandler 类能被扫描到并装载进 Spring 容器中。

 

2.2 @ExceptionHandler 注解声明异常处理方法
@ControllerAdvice
public class GlobalExceptionHandler {

 

@ExceptionHandler(Exception.class)
@ResponseBody
String handleException(){
return "Exception Deal!";
}
}
1
2
3
4
5
6
7
8
9
方法 handleException() 就会处理所有 Controller 层抛出的 Exception 及其子类的异常,这是最基本的用法了。

 

被 @ExceptionHandler 注解的方法的参数列表里,还可以声明很多种类型的参数,详见文档。其原型如下:

 

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {

 

/**
* Exceptions handled by the annotated method. If empty, will default to any
* exceptions listed in the method argument list.
*/
Class<? extends Throwable>[] value() default {};

 

}
1
2
3
4
5
6
7
8
9
10
11
12
如果 @ExceptionHandler 注解中未声明要处理的异常类型,则默认为参数列表中的异常类型。所以上面的写法,还可以写成这样:

 

@ControllerAdvice
public class GlobalExceptionHandler {

 

@ExceptionHandler()
@ResponseBody
String handleException(Exception e){
return "Exception Deal! " + e.getMessage();
}
}
1
2
3
4
5
6
7
8
9
参数对象就是 Controller 层抛出的异常对象!

 

三、处理 Service 层上抛的业务异常
有时我们会在复杂的带有数据库事务的业务中,当出现不和预期的数据时,直接抛出封装后的业务级运行时异常,进行数据库事务回滚,并希望该异常信息能被返回显示给用户。

 

3.1 代码示例
封装的业务异常类:

 

public class BusinessException extends RuntimeException {

 

public BusinessException(String message){
super(message);
}
}
1
2
3
4
5
6
Service 实现类:

 

@Service
public class DogService {

 

@Transactional
public Dog update(Dog dog){

 

// some database options

 

// 模拟狗狗新名字与其他狗狗的名字冲突
BSUtil.isTrue(false, "狗狗名字已经被使用了...");

 

// update database dog info

 

return dog;
}

 

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
其中辅助工具类 BSUtil

 

public static void isTrue(boolean expression, String error){
if(!expression) {
throw new BusinessException(error);
}
}
1
2
3
4
5
那么,我们应该在 GlobalExceptionHandler 类中声明该业务异常类,并进行相应的处理,然后返回给用户。更贴近真实项目的代码,应该长这样子:

 

/**
* Created by kinginblue on 2017/4/10.
* @ControllerAdvice + @ExceptionHandler 实现全局的 Controller 层的异常处理
*/
@ControllerAdvice
public class GlobalExceptionHandler {

 

private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

 

/**
* 处理所有不可知的异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
AppResponse handleException(Exception e){
LOGGER.error(e.getMessage(), e);

 

AppResponse response = new AppResponse();
response.setFail("操作失败!");
return response;
}

 

/**
* 处理所有业务异常
* @param e
* @return
*/
@ExceptionHandler(BusinessException.class)
@ResponseBody
AppResponse handleBusinessException(BusinessException e){
LOGGER.error(e.getMessage(), e);

 

AppResponse response = new AppResponse();
response.setFail(e.getMessage());
return response;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Controller 层的代码,就不需要进行异常处理了:

 

@RestController
@RequestMapping(value = "/dogs", consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public class DogController {

 

@Autowired
private DogService dogService;

 

@PatchMapping(value = "")
Dog update(@Validated(Update.class) @RequestBody Dog dog){
return dogService.update(dog);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
3.2 代码说明
Logger 进行所有的异常日志记录。

 

@ExceptionHandler(BusinessException.class) 声明了对 BusinessException 业务异常的处理,并获取该业务异常中的错误提示,构造后返回给客户端。

 

@ExceptionHandler(Exception.class) 声明了对 Exception 异常的处理,起到兜底作用,不管 Controller 层执行的代码出现了什么未能考虑到的异常,都返回统一的错误提示给客户端。

 

备注:以上 GlobalExceptionHandler 只是返回 Json 给客户端,更大的发挥空间需要按需求情况来做。

 

四、处理 Controller 数据绑定、数据校验的异常
在 Dog 类中的字段上的注解数据校验规则:

 

@Data
public class Dog {

 

@NotNull(message = "{Dog.id.non}", groups = {Update.class})
@Min(value = 1, message = "{Dog.age.lt1}", groups = {Update.class})
private Long id;

 

@NotBlank(message = "{Dog.name.non}", groups = {Add.class, Update.class})
private String name;

 

@Min(value = 1, message = "{Dog.age.lt1}", groups = {Add.class, Update.class})
private Integer age;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
说明:@NotNull、@Min、@NotBlank 这些注解的使用方法,不在本文范围内。如果不熟悉,请查找资料学习即可。

 

其他说明:
@Data 注解是 **Lombok** 项目的注解,可以使我们不用再在代码里手动加 getter & setter。
在 Eclipse 和 IntelliJ IDEA 中使用时,还需要安装相关插件,这个步骤自行Google/Baidu 吧!
1
2
3
4
5
Lombok 使用方法见:Java奇淫巧技之Lombok

 

SpringMVC 中对于 RESTFUL 的 Json 接口来说,数据绑定和校验,是这样的:

 

/**
* 使用 GlobalExceptionHandler 全局处理 Controller 层异常的示例
* @param dog
* @return
*/
@PatchMapping(value = "")
AppResponse update(@Validated(Update.class) @RequestBody Dog dog){
AppResponse resp = new AppResponse();

 

// 执行业务
Dog newDog = dogService.update(dog);

 

// 返回数据
resp.setData(newDog);

 

return resp;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
使用 @Validated + @RequestBody 注解实现。

 

当使用了 @Validated + @RequestBody 注解但是没有在绑定的数据对象后面跟上 Errors 类型的参数声明的话,Spring MVC 框架会抛出 MethodArgumentNotValidException 异常。

 

所以,在 GlobalExceptionHandler 中加上对 MethodArgumentNotValidException 异常的声明和处理,就可以全局处理数据校验的异常了!加完后的代码如下:

 

/**
* Created by kinginblue on 2017/4/10.
* @ControllerAdvice + @ExceptionHandler 实现全局的 Controller 层的异常处理
*/
@ControllerAdvice
public class GlobalExceptionHandler {

 

private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

 

/**
* 处理所有不可知的异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
AppResponse handleException(Exception e){
LOGGER.error(e.getMessage(), e);

 

AppResponse response = new AppResponse();
response.setFail("操作失败!");
return response;
}

 

/**
* 处理所有业务异常
* @param e
* @return
*/
@ExceptionHandler(BusinessException.class)
@ResponseBody
AppResponse handleBusinessException(BusinessException e){
LOGGER.error(e.getMessage(), e);

 

AppResponse response = new AppResponse();
response.setFail(e.getMessage());
return response;
}

 

/**
* 处理所有接口数据验证异常
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
AppResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
LOGGER.error(e.getMessage(), e);

 

AppResponse response = new AppResponse();
response.setFail(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return response;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
注意到了吗,所有的 Controller 层的异常的日志记录,都是在这个 GlobalExceptionHandler 中进行记录。也就是说,Controller 层也不需要在手动记录错误日志了。

 

五、总结
本文主要讲 @ControllerAdvice + @ExceptionHandler 组合进行的 Controller 层上抛的异常全局统一处理。

 

其实,被 @ExceptionHandler 注解的方法还可以声明很多参数,详见文档。

 

@ControllerAdvice 也还可以结合 @InitBinder、@ModelAttribute 等注解一起使用,应用在所有被 @RequestMapping 注解的方法上,详见搜索引擎。

 

六、附录
本文示例代码已放到 Github。

 

posted @ 2019-03-07 11:05  GordonDicaprio  阅读(10178)  评论(0编辑  收藏  举报