SpringMVC统一异常处理总结

在一个Spring MVC项目中,使用统一异常处理,可以使维护代码变得容易。下面总结一下常用的3种方法。
try-catch

实现HandlerExceptionResolver接口

实现HandlerExceptionResolver接口,实现resolveException()方法,根据传入的异常类型做出处理。

继承AbstractHandlerExceptionResolver

继承AbstractHandlerExceptionResolver类,和第一种方式类似,因为AbstractHandlerExceptionResolver实现了HandlerExceptionResolver接口。
所以,我们继承之后也是重写resolveException()方法,再处理各种异常。

使用注解@ControllerAdvice处理

推荐使用这种方法,比较直观。下面上代码:

首先是自定义异常类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class ResourceDoesNotExistException extends RuntimeException {
private static final long serialVersionUID = 7833283455112352655L;
public ResourceDoesNotExistException() {
super();
}
public ResourceDoesNotExistException(String message) {
super(message);
}
public ResourceDoesNotExistException(String message, Throwable cause) {
super(message, cause);
}
public ResourceDoesNotExistException(Throwable cause) {
super(cause);
}
protected ResourceDoesNotExistException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

然后是全局异常统一处理类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = OtherException.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception ex) {
// 其他异常处理逻辑...
}
@ExceptionHandler(value = ResourceDoesNotExistException.class)
public ModelAndView notFoundErrorHandler(HttpServletRequest req, ResourceDoesNotExistException ex) {
ModelAndView mav = new ModelAndView();
mav.setViewName("404");
return mav;
}
}

添加@ControllerAdvice注解的类是集中处理异常的地方,可以同时存在多个这样的类,用来做更细粒度的划分。
在这个类中,我们可以对每一种异常编写一种处理逻辑,在方法上使用@ExceptionHandler注解修饰,传入指定的异常类型即可。
如果是RESTful风格,不返回视图,也可使用@RestControllerAdvice