我是靠谱客的博主 妩媚水杯,这篇文章主要介绍spring-boot,全局异常统一拦截处理,现在分享给大家,希望可以做个参考。

外链:访问地址

1、创建自定义的异常RRException

复制代码
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.blog.common.utils; /** * @author wangfj * @date 2018-11-19 * @description 自定义异常 */ public class RRException extends RuntimeException { private static final long serialVersionUID = 1L; private String msg; private int code = 500; private Object data; public Object getData() { return data; } public void setData(Object data) { this.data = data; } public RRException(String msg) { super(msg); this.msg = msg; } public RRException(String msg, Throwable e) { super(msg, e); this.msg = msg; } public RRException(String msg, int code) { super(msg); this.msg = msg; this.code = code; } public RRException(String msg, int code, Throwable e) { super(msg, e); this.msg = msg; this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }

2、创建异常处理配置类MyExceptionHandler

复制代码
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
38
39
40
41
package com.blog.index.config; import com.blog.common.result.R; import com.blog.common.utils.RRException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; /** * @author wangfujie * @date 2018-12-12 16:45 * @description 全局异常捕获处理 */ @ControllerAdvice public class MyExceptionHandler { /** * 统一异常处理 * @param e * @return */ @ResponseBody @ExceptionHandler(value = Exception.class) public Object errorHandler(Exception e){ e.printStackTrace(); return R.error(110, e.getMessage()); } /** * 自定义异常的处理 * @param e * @return */ @ResponseBody @ExceptionHandler(value = RRException.class) public Object myErrorHandler(RRException e){ e.printStackTrace(); return R.error(e.getCode(), e.getMsg()); } }

3、在代码中手动抛出异常即可

复制代码
1
2
throw new RRException("该用户没有权限!", 504);

4、返回效果

复制代码
1
2
{"msg":"该用户没有权限!","code":504,"needRefresh":true}

在这里插入图片描述

最后

以上就是妩媚水杯最近收集整理的关于spring-boot,全局异常统一拦截处理的全部内容,更多相关spring-boot内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(57)

评论列表共有 0 条评论

立即
投稿
返回
顶部