---
title: "spring mvc统一异常处理（@ControllerAdvice + @ExceptionHandler）"
author: "m635674608"
date: "2017-12-01T17:09:13Z"
tags: []
categories: ["编程语言"]
slug: "spring-mvc-controlleradvice-exceptionhandler"
draft: false
lastmod: "2017-12-01T18:05:42Z"
id: 2401604
url: "https://m635674608.iteye.com/blog/2401604"
---

spring 封装了非常强大的异常处理机制。本文选取@ControllerAdvice + @ExceptionHandler 这种零配置（全注解），作为异常处理解决方案！

 

@ControllerAdvice，是spring3.2提供的新注解，从名字上可以看出大体意思是控制器增强。让我们先看看@ControllerAdvice的实现：

1

2

3

4

5

`@Target(value=TYPE)`

`@Retention(value=RUNTIME)`

`@Documented`

`@Component`

`public` `@interface` `ControllerAdvice`

 

(spring 官方解释)

![](http://images2015.cnblogs.com/blog/724399/201612/724399-20161201200034615-1622133390.png)

即把@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最有用，另外两个用处不大。

 

 

接下来看段代码：

 

Java代码  [![收藏代码](http://jinnianshilongnian.iteye.com/images/icon_star.png)]()

01. @ControllerAdvice
02. public class ControllerAdviceTest {
03. @ModelAttribute
04. public User newUser() {
05. System.out.println("============应用到所有@RequestMapping注解方法，在其执行之前把返回值放入Model");
06. return new User();
07. }
08. @InitBinder
09. public void initBinder(WebDataBinder binder) {
10. System.out.println("============应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器");
11. }
12. @ExceptionHandler(UnauthenticatedException.class)
13. @ResponseStatus(HttpStatus.UNAUTHORIZED)
14. public String processUnauthenticatedException(NativeWebRequest request, UnauthenticatedException e) {
15. System.out.println("===========应用到所有@RequestMapping注解的方法，在其抛出UnauthenticatedException异常时执行");
16. return "viewName"; //返回一个逻辑视图名
17. }
18. }

这样可以全局的管理项目的异常现象，避免的错误信息直接显示到页面的尴尬。

参考：

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html

 

 

https://www.cnblogs.com/chihirotan/p/5990742.html