@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": ...
随机推荐
- Redis入门到高可用(十九)——Redis Sentinel
一.Redis Sentinel架构 二.redis sentinel安装与配置 四.客户端连接Sentinel 四.实现原理—— 故障转移演练(客户端高可用) 五.实 ...
- python框架之Django(16)-接入Redis
准备 安装Redis 参考 Ubuntu 中 Redis 的安装与使用. 在python中使用Redis 参考 python 中使用 Redis . 安装依赖包 在 Django 中接入 Redis ...
- Hive为什么要启用Metastore?
转载来自: https://blog.csdn.net/qq_40990732/article/details/80914873 https://blog.csdn.net/tp15868352616 ...
- shmdt() 与 shmctl() 的区别?
操作共享内存,我们用到了下面的函数 ============================================== #include <sys/types.h> #inclu ...
- JDK 1.8源码阅读 HashSet
一,前言 类实现Set接口,由哈希表支持(实际上是一个 HashMap集合).HashSet集合不能保证的迭代顺序与元素存储顺序相同.HashSet集合,采用哈希表结构存储数据,保证元素唯一性的方式依 ...
- AppFabric查询工作流实例
安装 通过IIS查询工作流实例,可以操作挂起,首先打开WF+WCF的站点: 这里可以搜索工作流实例:例如根据工作流ID.创建日期.状态等查询 下方的搜索结果可以查看结果 资源 Windows Serv ...
- android 前台服务不显示通知
原因可以在哪里写了执行完成后就自动结束的吧 导致前台服务没有出现 如我 @Override public int onStartCommand(Intent intent, int flags, in ...
- fiddler学习总结--autoresponder替换资源
意义:替换服务器返回的内容 1.找到需要替换的目标 2.选择目标后,点击“autoresponder”-->”add rules” 3.在下图中,选择“find a file”,再选择需要替换 ...
- sublime-text3按tab跳出括号
功能 通过按tab自动跳过右括号,右引号,虽然也可以按右方向键,但离得太远按起来太麻烦 在首选项->按键绑定里添加: { "keys": ["tab"], ...
- linux关闭终端响铃
title: linux关闭终端响铃 date: 2018-01-25 15:10:14 tags: linux categories: linux 在终端输入或是直接在.bashrc里添加一行 xs ...