
在实际项目开发中,我们会遇到各种各样的异常,如果我们对这些异常不做处理直接暴露给用户的话,肯定是一种不好的体验,所以我们想办法捕获异常。最常见的方法是用try-catch 来捕获异常并设置返回信息,但是我们如果每个异常都去try-catch的话,无异是一件很费力的事情,所以我们有必要寻找一个可以处理全局异常的方法…
使用工具
- IntelliJ IDEA 2018.1 x64
- jdk8
- SpringBoot 2.0.3
添加依赖
1 | dependencies> |
创建异常返回信息模板ErrorResponseEntity
1 | /** |
创建自定义异常TestException
1 | /** |
创建全局处理异常GlobalExceptionHandler
注解说明
-@ControllerAdvice捕获Controller层抛出的异常,如果添加@ResponseBody返回信息则为JSON格式。
-@RestControllerAdvice相当于 @ControllerAdvice 与 @ResponseBody的结合体。
-@ExceptionHandler统一处理一种类的异常,减少代码重复率,降低复杂度。
1 | /** |
测试
创建TestController1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16/**
* @author :mathias
* Description:测试全局异常
* Date: 2018/6/19
*/
public class TestController {
("/testException")
public String testException(Integer num ){
if (num == null){
throw new TestException(400,"num 不能为空");
}
int i = 10 / num;
return "result: "+ i;
}
}
这里当num = null的时候就抛出我们的自定义异常,然后全局异常捕获,返回我们异常模板的信息。启动项目,访问http://localhost:8080/testException,返回结果1
2
3
4{
"code": 400,
"msg": "num 不能为空"
}
再访问 http://localhost:8080/testException?num=0,返回结果1
2
3
4{
"code": 400,
"msg": "/ by zero"
}
访问 http://localhost:8080/testException?num=2,返回结果1
result: 5
好了,这样就完成了我们的全局异常处理。
结尾
文章参考自 http://blog.battcn.com/2018/06/01/springboot/v2-other-exception/