SpringBoot2.3.12.RELEASE优雅的全局异常处理(模板⼀)
1、⾸先,需要引⼊maven依赖包,如下所⽰:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="/POM/4.0.0"
3 xmlns:xsi="/2001/XMLSchema-instance"
4 xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd">
5 <modelVersion>4.0.0</modelVersion>
6 <parent>
7 <groupId>org.springframework.boot</groupId>
8 <artifactId>spring-boot-starter-parent</artifactId>
9 <version>2.3.12.RELEASE</version>
10 <relativePath /> <!-- lookup parent from repository -->
11 </parent>
12 <groupId>com.bie</groupId>
13 <artifactId>SpringbootException</artifactId>
14 <version>0.0.1-SNAPSHOT</version>
15 <name>SpringbootException</name>
16 <description>Demo project for Spring Boot</description>
17
18 <properties>
19 <java.version>1.8</java.version>
20 </properties>
21
22 <dependencies>
23 <!-- 引⼊springboot web模块 -->
24 <dependency>
25 <groupId>org.springframework.boot</groupId>
26 <artifactId>spring-boot-starter-web</artifactId>
27 </dependency>
28 <!-- 引⼊fastjson的依赖 -->
29 <dependency>
30 <groupId>com.alibaba</groupId>
31 <artifactId>fastjson</artifactId>
32 <version>1.2.41</version>
33 </dependency>
34
35 <dependency>
36 <groupId>org.springframework.boot</groupId>
37 <artifactId>spring-boot-starter-test</artifactId>
38 <scope>test</scope>
39 <exclusions>
40 <exclusion>
41 <groupId>org.junit.vintage</groupId>
42 <artifactId>junit-vintage-engine</artifactId>
43 </exclusion>
44 </exclusions>
45 </dependency>
46 </dependencies>
47
48 <build>
49 <plugins>
50 <plugin>
51 <groupId>org.springframework.boot</groupId>
52 <artifactId>spring-boot-maven-plugin</artifactId>
53 </plugin>
54 </plugins>
55 </build>
56
57 </project>
SpringBoot中有⼀个ControllerAdvice的注解,使⽤该注解表⽰开启了全局异常的捕获,我们只需再⾃定义⼀个⽅法,然后使⽤ExceptionHandler注解,在该注解的value属性⾥⾯,定义捕获异常的类型,即可对这些捕获的异常进⾏统⼀的处理。
2、⾃定义基础接⼝类。
⾸先定义⼀个基础的接⼝类,⾃定义的错误描述枚举类需实现该接⼝。
1 package ums;
2
3public interface BaseErrorInfoInterface {
4
5// 错误码
6public String getResultCode();
7
8// 错误描述
9public String getResultMsg();
10
11 }
3、⾃定义枚举类。
然后我们这⾥在⾃定义⼀个枚举类,并实现该接⼝。⽽使⽤枚举类的好处是处理异常的时候,可以通过枚举类直接获取到错误码、错误描述,⽅便调⽤。
1 package ums;
2
3public enum CommonEnum implements BaseErrorInfoInterface {
4
5// 数据操作错误定义
6 SUCCESS("200", "接⼝调⽤成功!"),
7
8 BODY_NOT_MATCH("400", "请求的数据格式不符!"),
9
10 SIGNATURE_NOT_MATCH("401", "请求的数字签名不匹配!"),
11
12 NOT_FOUND("404", "未到该资源!"),
13
14 INTERNAL_SERVER_ERROR("500", "服务器内部错误!"),
15
16 SERVER_BUSY("503", "服务器正忙,请稍后再试!");
17
18// 错误码
19private String resultCode;
20
21// 错误描述
22private String resultMsg;
23
24 CommonEnum(String resultCode, String resultMsg) {
27 }
28
29 @Override
30public String getResultCode() {
31return resultCode;
32 }
33
34 @Override
35public String getResultMsg() {
36return resultMsg;
37 }
38
39 }
4、⾃定义异常类。
然后我们在来⾃定义⼀个异常类,⽤于处理我们发⽣的业务异常。
1 package ption;
2
3 import ums.BaseErrorInfoInterface;
4
5public class BizException extends RuntimeException {
6
7/**
8 *
9*/
10private static final long serialVersionUID = -6329783845738305585L;
11
12// 错误码
13protected String errorCode;
14// 错误信息
15protected String errorMsg;
16
17public BizException() {
18 super();
19 }
20
21public BizException(BaseErrorInfoInterface errorInfoInterface) {
22 ResultCode());
25 }
26
27public BizException(BaseErrorInfoInterface errorInfoInterface, Throwable cause) {
28 ResultCode(), cause);
31 }
32
33public BizException(String errorMsg) {
34 super(errorMsg);
36 }
37
38public BizException(String errorCode, String errorMsg) {
39 super(errorCode);
42 }
43
44public BizException(String errorCode, String errorMsg, Throwable cause) {
45 super(errorCode, cause);
48 }
49
50public String getErrorCode() {
51return errorCode;
52 }
53
54public void setErrorCode(String errorCode) {
56 }
57
58public String getErrorMsg() {
59return errorMsg;
60 }
61
62public void setErrorMsg(String errorMsg) {
64 }
65
66public String getMessage() {
67return errorMsg;
68 }
69
70 @Override
71public Throwable fillInStackTrace() {
72return this;
73 }
74
75 }
5、⾃定义数据格式。
顺便这⾥我们定义⼀下数据的传输格式,作⽤主要⽤于返回给前端的数据格式。
1 package com.bie.utils;
2
3 import com.alibaba.fastjson.JSONObject;
4 import ums.BaseErrorInfoInterface;
5 import ums.CommonEnum;
6
7public class ResultBody {
8
9// 响应代码
10private String code;
11
12// 响应消息
13private String message;
14
15// 响应结果
16private Object result;
17
18public ResultBody() {
19 }
20
21public ResultBody(BaseErrorInfoInterface errorInfo) {
24 }
25
26public String getCode() {
27return code;
28 }
29
30public void setCode(String code) {
32 }
33
34public String getMessage() {
35return message;
36 }
37
38public void setMessage(String message) {
40 }
41
42public Object getResult() {
43return result;
44 }
45
46public void setResult(Object result) {
48 }
49
50/**
51 * 成功
52 *
53 * @return
54*/
55public static ResultBody success() {
56return success(null);
57 }
58
59/**
60 * 成功
61 *
62 * @param data
63 * @return
64*/
65public static ResultBody success(Object data) {
66 ResultBody rb = new ResultBody();
67 rb.setCode(ResultCode());
68 rb.setMessage(ResultMsg());
69 rb.setResult(data);
70return rb;
71 }
72
73/**
74 * 失败
75*/
76public static ResultBody error(BaseErrorInfoInterface errorInfo) {
77 ResultBody rb = new ResultBody();
78 rb.ResultCode());
79 rb.ResultMsg());
80 rb.setResult(null);
81return rb;
82 }
83
84/**
85 * 失败
86*/
87public static ResultBody error(String code, String message) {
88 ResultBody rb = new ResultBody();
89 rb.setCode(code);
90 rb.setMessage(message);
91 rb.setResult(null);
92return rb;
93 }
94
95/**
96 * 失败
97*/
98public static ResultBody error(String message) {
99 ResultBody rb = new ResultBody();
100 rb.setCode("-1");
101 rb.setMessage(message);
102 rb.setResult(null);
103return rb;
104 }
105
106 @Override
107public String toString() {
JSONString(this);
109 }
110
111 }
6、⾃定义全局异常处理类。
最后我们再来编写⼀个⾃定义全局异常处理的类,可以⽤于处理各类异常。
1 package ption;
2
3 import javax.servlet.http.HttpServletRequest;
4
5 import org.slf4j.Logger;
6 import org.slf4j.LoggerFactory;
7 import org.springframework.web.bind.annotation.ControllerAdvice;
8 import org.springframework.web.bind.annotation.ExceptionHandler;
9 import org.springframework.web.bind.annotation.ResponseBody;
10
11 import ums.CommonEnum;
12 import com.bie.utils.ResultBody;
13
14 @ControllerAdvice
15public class GlobalExceptionHandler {
16
17private static final Logger logger = Logger(GlobalExceptionHandler.class);
18
19/**
20 * 处理⾃定义的业务异常
21 *
22 * @param req
23 * @param e
24 * @return
25*/
26 @ExceptionHandler(value = BizException.class)
27 @ResponseBody
28public ResultBody bizExceptionHandler(HttpServletRequest req, BizException e) {
29 ("发⽣业务异常!原因是:{}", e.getErrorMsg());
(e.getErrorCode(), e.getErrorMsg());
31 }
32
33/**
34 * 处理空指针的异常
35 *
36 * @param req
37 * @param e
38 * @return
39*/
40 @ExceptionHandler(value = NullPointerException.class)
41 @ResponseBody
42public ResultBody exceptionHandler(HttpServletRequest req, NullPointerException e) {
43 ("发⽣空指针异常!原因是:", e);
(CommonEnum.BODY_NOT_MATCH);
45 }
46
47/**
48 * 处理其他异常
49 *
50 * @param req
51 * @param e
52 * @return
53*/
54 @ExceptionHandler(value = Exception.class)
55 @ResponseBody
56public ResultBody exceptionHandler(HttpServletRequest req, Exception e) {
57 ("未知异常!原因是:", e);
(CommonEnum.INTERNAL_SERVER_ERROR);
59 }
60
61 }
7、创建⼀个⽤户的实体类,如下所⽰:
1 package com.bie.po;
2
3 import java.io.Serializable;
4
5 import com.alibaba.fastjson.JSONObject;
6
7public class User implements Serializable {
8
9/**
10 *
11*/
12private static final long serialVersionUID = 1360679426784375558L;
13
14// 编号
15private int id;
16// 姓名
17private String name;
18// 年龄
19private int age;
20
21public User() {
22 }
23
24public int getId() {
25return id;
26 }
27
28public void setId(int id) {
29this.id = id;
30 }
31
32public String getName() {
33return name;
34 }
35
36public void setName(String name) {
37this.name = name;
38 }
39
40public int getAge() {
41return age;
42 }
43
44public void setAge(int age) {
45this.age = age;
46 }
47
48public String toString() {
JSONString(this);
50 }
51
52 }
8、Controller 控制层。
控制层这边也⽐较简单,使⽤Restful风格实现的CRUD功能,主要是Restful风格的,根据请求⽅式get、post、put、delete,⽽请求路径是⼀个,主要根据请求⽅式来做区分操作。
1 package ller;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import org.springframework.web.bind.annotation.DeleteMapping;
7 import org.springframework.web.bind.annotation.GetMapping;
8 import org.springframework.web.bind.annotation.PostMapping;
9 import org.springframework.web.bind.annotation.PutMapping;
10 import org.springframework.web.bind.annotation.RequestBody;
11 import org.springframework.web.bind.annotation.RequestMapping;
12 import org.springframework.web.bind.annotation.RestController;
13
14 import ption.BizException;
15 import com.bie.po.User;
16
17 @RestController
18 @RequestMapping(value = "/api")
19public class UserRestController {
20
21 @PostMapping("/user")
22public boolean insert(@RequestBody User user) {
23 System.out.println("开始新增...");
24// 如果姓名为空就⼿动抛出⼀个⾃定义的异常!
25if (Name() == null) {
26throw new BizException("-1", "⽤户姓名不能为空!");
27 }
28return true;
29 }
30
31 @PutMapping("/user")
32public boolean update(@RequestBody User user) {
33 System.out.println("开始更新...");
34// 这⾥故意造成⼀个空指针的异常,并且不进⾏处理
35 String str = null;
36 str.equals("111");
37return true;
38 }
39
40 @DeleteMapping("/user")
41public boolean delete(@RequestBody User user) {
42 System.out.println("开始删除...");
43// 这⾥故意造成⼀个异常,并且不进⾏处理
44 Integer.parseInt("abc123");
45return true;
46 }
spring framework版本47
48 @GetMapping("/user")
49public List<User> findByUser(User user) {
50 System.out.println("开始查询...");
51 List<User> userList = new ArrayList<>();
52 User user2 = new User();
53 user2.setId(1);
54 user2.setName("xuwujing");
55 user2.setAge(18);
56 userList.add(user2);
57return userList;
58 }
59
60 }
9、接⼝功能测试,使⽤postman进⾏测试,如下所⽰:
9.1、⾸先进⾏查询,查看程序是否正常运⾏,使⽤GET ⽅式进⾏请求,如下所⽰:
9.2、进⾏插⼊操作,使⽤POST⽅式进⾏请求,如下所⽰:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论