@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常
@ControllerAdvice 和 @ExceptionHandler 的区别
ExceptionHandler, 方法注解, 作用于 Controller 级别. ExceptionHandler 注解为一个 Controler 定义一个异常处理器.
ControllerAdvice, 类注解, 作用于 整个 Spring 工程. ControllerAdvice 注解定义了一个全局的异常处理器.
需要注意的是, ExceptionHandler 的优先级比 ControllerAdvice 高, 即 Controller 抛出的异常如果既可以让 ExceptionHandler 标注的方法处理, 又可以让 ControllerAdvice 标注的类中的方法处理, 则优先让 ExceptionHandler 标注的方法处理.
处理 Controller 中的异常
为了方便地展示 Controller 异常处理的方式, 我创建了一个工程 SpringBootRESTfulErrorHandler, 其源码可以到我的 Github: github.com/yongshun 中找到.
SpringBootRESTfulErrorHandler 工程的目录结构如下:

首先我们定义了三个自定义的异常:
BaseException:
|
1
2
3
4
5
|
public class BaseException extends Exception { public BaseException(String message) { super(message); }} |
MyException1:
|
1
2
3
4
5
|
public class MyException1 extends BaseException { public MyException1(String message) { super(message); }} |
MyException2:
|
1
2
3
4
5
|
public class MyException2 extends BaseException { public MyException2(String message) { super(message); }} |
接着我们在 DemoController 中分别抛出这些异常:
|
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
|
@RestControllerpublic class DemoController { private Logger logger = LoggerFactory.getLogger("GlobalExceptionHandler"); @RequestMapping("/ex1") public Object throwBaseException() throws Exception { throw new BaseException("This is BaseException."); } @RequestMapping("/ex2") public Object throwMyException1() throws Exception { throw new MyException1("This is MyException1."); } @RequestMapping("/ex3") public Object throwMyException2() throws Exception { throw new MyException2("This is MyException1."); } @RequestMapping("/ex4") public Object throwIOException() throws Exception { throw new IOException("This is IOException."); } @RequestMapping("/ex5") public Object throwNullPointerException() throws Exception { throw new NullPointerException("This is NullPointerException."); } @ExceptionHandler(NullPointerException.class) public String controllerExceptionHandler(HttpServletRequest req, Exception e) { logger.error("---ControllerException Handler---Host {} invokes url {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(), e.getMessage()); return e.getMessage(); }} |
/ex1: 抛出 BaseException
/ex2: 抛出 MyException1
/ex3: 抛出 MyException2
/ex4: 抛出 IOException
/ex5: 抛出 NullPointerException
当 DemoController 抛出未捕获的异常时, 我们在 GlobalExceptionHandler 中进行捕获并处理:
GlobalExceptionHandler:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@RestController@ControllerAdvicepublic class GlobalExceptionHandler { private Logger logger = LoggerFactory.getLogger("GlobalExceptionHandler"); @ExceptionHandler(value = BaseException.class) @ResponseBody public Object baseErrorHandler(HttpServletRequest req, Exception e) throws Exception { logger.error("---BaseException Handler---Host {} invokes url {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(), e.getMessage()); return e.getMessage(); } @ExceptionHandler(value = Exception.class) @ResponseBody public Object defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { logger.error("---DefaultException Handler---Host {} invokes url {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(), e.getMessage()); return e.getMessage(); }} |
我们看到, GlobalExceptionHandler 类有两个注解:
RestController, 表明 GlobalExceptionHandler 是一个 RESTful Controller, 即它会以 RESTful 的形式返回回复.
ControllerAdvice, 表示 GlobalExceptionHandler 是一个全局的异常处理器.
在 GlobalExceptionHandler 中, 我们使用了 ExceptionHandler 注解标注了两个方法:
ExceptionHandler(value = BaseException.class): 表示 baseErrorHandler 处理 BaseException 异常和其子异常.
ExceptionHandler(value = Exception.class): 表示 defaultErrorHandler 会处理 Exception 异常和其所用子异常.
要注意的是, 和 try...catch 语句块, 异常处理的顺序也是从具体到一般, 即如果 baseErrorHandler 可以处理此异常, 则调用此方法来处理异常, 反之使用 defaultErrorHandler 来处理异常.
既然我们已经实现了 Controller 的异常处理, 那么接下来我们就来测试一下吧.
在浏览器中分别访问这些链接, 结果如下:
/ex1:

/ex2:

/ex3:

/ex4:

/ex5:

可以看到, /ex1, /ex2, /ex3 抛出的异常都由 GlobalExceptionHandler.baseErrorHandler 处理; /ex4 抛出的 IOException 异常由 GlobalExceptionHandler.defaultErrorHandler 处理. 但是 /ex5 抛出的 NullPointerException 异常为什么不是 defaultErrorHandler 处理, 而是由 controllerExceptionHandler 来处理呢? 回想到 @ControllerAdvice 和 @ExceptionHandler 的区别 这以小节中的内容时, 我们就知道原因了: 因为我们在 DemoController 中使用 ExceptionHandler 注解定义了一个 Controller 级的异常处理器, 这个级别的异常处理器的优先级比全局的异常处理器优先级高, 因此 Spring 发现 controllerExceptionHandler 可以处理 NullPointerException 异常时, 就调用这个方法, 而不会调用全局的 defaultErrorHandler 方法了.
处理 404 错误
Spring MVC
SpringBoot 默认提供了一个全局的 handler 来处理所有的 HTTP 错误, 并把它映射为 /error. 当发生一个 HTTP 错误, 例如 404 错误时, SpringBoot 内部的机制会将页面重定向到 /error 中.
例如下图中是一个默认的 SpringBoot 404 异常页面.

这个页面实在是太丑了, 我们能不能自定义一个异常页面呢? 当然可以了, 并且 SpringBoot 也给我们提示了: This application has no explicit mapping for /error, so you are seeing this as a fallback.
因此我们实现一个 /error 映射的 Controller 即可.
|
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
|
public class HttpErrorHandler implements ErrorController { private final static String ERROR_PATH = "/error"; /** * Supports the HTML Error View * * @param request * @return */ @RequestMapping(value = ERROR_PATH, produces = "text/html") public String errorHtml(HttpServletRequest request) { return "404"; } /** * Supports other formats like JSON, XML * * @param request * @return */ @RequestMapping(value = ERROR_PATH) @ResponseBody public Object error(HttpServletRequest request) { return "404"; } /** * Returns the path of the error page. * * @return the error path */ @Override public String getErrorPath() { return ERROR_PATH; }} |
根据上面代码我们看到, 为了实现自定义的 404 页面, 我们实现了 ErrorController 接口:
|
1
2
3
|
public interface ErrorController { String getErrorPath();} |
这个接口只有一个方法, 当出现 HTTP 错误时, SpringBoot 会将页面重定向到 getErrorPath 方法返回的页面中. 这样我们就可以实现自定义的错误页面了.
RESTful API
提供一个自定义的 "/error" 页面对 Spring MVC 的服务来说自然是没问题的, 但是如果我们的服务是一个 RESTful 服务的话, 这样做就不行了.
当用户调用了一个不存在的 RESTful API 时, 我们想记录下这个异常访问, 并返回一个代表错误的 JSON 给客户端, 这该怎么实现呢?
我们很自然地想到, 我们可以使用处理异常的那一套来处理 404 错误码.
那么我们来试一下这个想法是否可行吧.

奇怪的是, 当我们在浏览器中随意输入一个路径时, 代码并没有执行到异常处理逻辑中, 而是返回了一个 HTML 页面给我们, 这又是怎么回事呢?
原来 Spring Boot 中, 当用户访问了一个不存在的链接时, Spring 默认会将页面重定向到 **/error** 上, 而不会抛出异常.
既然如此, 那我们就告诉 Spring Boot, 当出现 404 错误时, 抛出一个异常即可. 在 application.properties 中添加两个配置:
|
1
2
|
spring.mvc.throw-exception-if-no-handler-found=truespring.resources.add-mappings=false |
上面的配置中, 第一个 spring.mvc.throw-exception-if-no-handler-found 告诉 SpringBoot 当出现 404 错误时, 直接抛出异常. 第二个 spring.resources.add-mappings 告诉 SpringBoot 不要为我们工程中的资源文件建立映射. 这两个配置正是 RESTful 服务所需要的.
当加上这两个配置后, 我们再来试一下:

可以看到, 现在确实是在 defaultErrorHandler 中处理了.
参考
https://www.cnblogs.com/Zombie-Xian/p/6251189.html
https://blog.csdn.net/smithallenyu/article/details/72331387
https://blog.csdn.net/kinginblue/article/details/70186586
https://blog.csdn.net/qq_17586821/article/details/79831244
https://www.cnblogs.com/shanheyongmu/p/5872442.html
@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常的更多相关文章
- @ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常==》记录
对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚. 如此一来, ...
- 转:@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常
继承 ResponseEntityExceptionHandler 类来实现针对 Rest 接口 的全局异常捕获,并且可以返回自定义格式: 复制代码 1 @Slf4j 2 @ControllerAdv ...
- 【统一异常处理】@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常
1.利用springmvc注解对Controller层异常全局处理 对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service ...
- @ControllerAdvice + @ExceptionHandler全局处理Controller层异常
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind ...
- @ControllerAdvice + @ExceptionHandler 处理 全部Controller层异常
对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚. 如此一来, ...
- SpringBoot入门教程(十九)@ControllerAdvice+@ExceptionHandler全局捕获Controller异常
在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder.@ModelAttribute,并应用到所有@Requ ...
- Spring @ControllerAdvice @ExceptionHandler 全局处理异常
对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚. 如此一来, ...
- (转)springboot全局处理异常(@ControllerAdvice + @ExceptionHandler)
1.@ControllerAdvice 1.场景一 在构建RestFul的今天,我们一般会限定好返回数据的格式比如: { "code": 0, "data": ...
- 十四、springboot全局处理异常(@ControllerAdvice + @ExceptionHandler)
1.@ControllerAdvice 1.场景一 在构建RestFul的今天,我们一般会限定好返回数据的格式比如: { "code": 0, "data": ...
随机推荐
- Vue2.0 v-for 中 :key 到底有什么用?
要解释 key 的作用,不得不先介绍一下虚拟 DOM 的 Diff 算法了. vue 和 react 的虚拟 DOM 的Diff算法大致相同,其核心是基于两个简单的假设: 1.两个相同的组件产生类似的 ...
- 【JVM】-NO.110.JVM.1 -【JDK11 HashMap详解】
Style:Mac Series:Java Since:2018-09-10 End:2018-09-10 Total Hours:1 Degree Of Diffculty:5 Degree Of ...
- Streaming从Spark2X迁移到Spark1.5 summary
配置文件的加载是一个难点,在local模式下非常容易,但是submit后一直报找不到文件,后来采用将properties文件放在加载类同一个package下,打包到同一个jar中解决. import ...
- Windows下安装MySql5.7(解压版本)
Windows下安装MySql5.7(解压版本) 1. 官方地址下载MySql Server 5.7 2. 解压文件到目录d:\Soft\mysql57下 3. 在上面目录下创建文件my.ini,内容 ...
- 防火墙iptables 设置
在服务器上架了一个tomcat,指定好端口号,我就开始访问,未果! 公司对服务器(RedHat)端口限制,可谓是滴水不漏! 用iptables 查看防火墙设置: Shell代码 iptables -n ...
- C#计算两个时间年份月份差
C#计算两个时间年份月份差 https://blog.csdn.net/u011127019/article/details/79142612
- Kubernetes代码解读-apiserver之list-watch
list-watch,作为k8s系统中统一的异步消息传递方式,对系统的性能.数据一致性起到关键性的作用.今天我想从代码这边探究一下list-watch的实现方式.并看是否能在后面的工作中优化这个过程. ...
- WDCP面板Web环境安装redis与phpredis扩展应用方法
http://www.ctyun.cn/bbs/thread-2882-1-1.html根据网友的要求需要在WDCP面板环境中安装人人商城程序,但是这个程序需要支持redis与phpredis扩展.根 ...
- Java 运行时字符编码与解码
以下仅为个人学习的记录,如有疏漏不妥之处,还请不吝赐教. Java在运行时字符char采用UTF-16进行编码. public class RuntimeEncoding { public stati ...
- Ubuntu 18.04拨号上网及校园网开启IPV6
Ubuntu 18.04下有两种方法实现拨号上网,第一种是通过图形界面添加,需要开启自动连接,并且要关闭以太网的自动连接.(不推荐这种连接方式)这里介绍第二种,通过pppoeconf命令进行拨号. 关 ...