spring mvc统一异常处理(@ControllerAdvice + @ExceptionHandler)
spring 封装了非常强大的异常处理机制。本文选取@ControllerAdvice + @ExceptionHandler 这种零配置(全注解),作为异常处理解决方案!
@ControllerAdvice,是spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强。让我们先看看@ControllerAdvice的实现:
1
2
3
4
5
|
@Target (value=TYPE)
@Retention (value=RUNTIME)
@Documented @Component public @interface ControllerAdvice
|
(spring 官方解释)
即把@ControllerAdvice注解内部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法应用到所有的 @RequestMapping注解的方法。非常简单,不过只有当使用@ExceptionHandler最有用,另外两个用处不大。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@ControllerAdvice public class ControllerExceptionHanler {
private static Logger logger = LoggerFactory.getLogger(ControllerExceptionHanler. class );
@ExceptionHandler (value=ApplicationRuntimeException. class )
public ResponseEntity<String> handleServiceException(Exception exception, HttpServletRequest request) {
return new ResponseEntity<String>(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler (value=Exception. class )
@ResponseStatus (value=HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<String> handleException(Exception exception, HttpServletRequest request) {
logger.error( "系统异常!" , exception);
return new ResponseEntity<String>( "操作失败,请联系管理员!" , HttpStatus.INTERNAL_SERVER_ERROR);
}
} |
即把@ControllerAdvice注解内部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法应用到所有的 @RequestMapping注解的方法。非常简单,不过只有当使用@ExceptionHandler最有用,另外两个用处不大。
接下来看段代码:
- @ControllerAdvice
- public class ControllerAdviceTest {
- @ModelAttribute
- public User newUser() {
- System.out.println("============应用到所有@RequestMapping注解方法,在其执行之前把返回值放入Model");
- return new User();
- }
- @InitBinder
- public void initBinder(WebDataBinder binder) {
- System.out.println("============应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器");
- }
- @ExceptionHandler(UnauthenticatedException.class)
- @ResponseStatus(HttpStatus.UNAUTHORIZED)
- public String processUnauthenticatedException(NativeWebRequest request, UnauthenticatedException e) {
- System.out.println("===========应用到所有@RequestMapping注解的方法,在其抛出UnauthenticatedException异常时执行");
- return "viewName"; //返回一个逻辑视图名
- }
- }
这样可以全局的管理项目的异常现象,避免的错误信息直接显示到页面的尴尬。
参考:
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html
https://www.cnblogs.com/chihirotan/p/5990742.html