springboot全局异常处理

  1. 1. 方法一:
    1. 1.1. CodeMsg.java
    2. 1.2. GlobalExceptionHandler.java
    3. 1.3. Result.java
  2. 2. 方法二:
    1. 2.1. Result.java
    2. 2.2. BaseErrorInfoInterface.java
    3. 2.3. CommonEnum.java
    4. 2.4. BizException.java
    5. 2.5. GlobalExceptionHandler.java
    6. 2.6. 测试:

方法一:

CodeMsg.java
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
62
63
64
65
66
67
68
69
70
71
72
package com.example.testspringboot.exption;

public class BizException extends RuntimeException{
private static final long serialVersionUID = 1L;

/**
* 错误码
*/
protected String errorCode;
/**
* 错误信息
*/
protected String errorMsg;

public BizException() {
super();
}

public BizException(BaseErrorInfoInterface errorInfoInterface) {
super(errorInfoInterface.getResultCode());
this.errorCode = errorInfoInterface.getResultCode();
this.errorMsg = errorInfoInterface.getResultMsg();
}

public BizException(BaseErrorInfoInterface errorInfoInterface, Throwable cause) {
super(errorInfoInterface.getResultCode(), cause);
this.errorCode = errorInfoInterface.getResultCode();
this.errorMsg = errorInfoInterface.getResultMsg();
}

public BizException(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}

public BizException(String errorCode, String errorMsg) {
super(errorCode);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}

public BizException(String errorCode, String errorMsg, Throwable cause) {
super(errorCode, cause);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}




public String getErrorCode() {
return errorCode;
}

public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}

public String getErrorMsg() {
return errorMsg;
}

public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}

@Override
public Throwable fillInStackTrace() {
return this;
}

}
GlobalExceptionHandler.java
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
package com.example.testspringboot.exption;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* Validated 校验错误异常处理。
* ExceptionHandler:注解中可以添加参数,参数是某个异常类的class,
* 代表这个方法专门处理该类异常。表示只有方法抛出 Exception 时,才会调用该方法。
* @param e
*/
@ExceptionHandler(value = BindException.class)
public Result exceptionHandler(BindException e){
Result result = new Result();
// 绑定异常是需要明确提示给用户的
if(e instanceof BindException){
BindException exception=(BindException) e;
List<ObjectError> errors=exception.getAllErrors();
String msg=errors.get(0).getDefaultMessage();//获取自错误信息
return Result.error(CodeMsg.SERVER_BIND_ERROR.fillArgs(msg)); //将具体错误信息设置到 CodeMsg中返回
}
// 其余异常简单返回为服务器异常
return Result.error(CodeMsg.SERVER_ERROR);
}


}
Result.java
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
package com.example.testspringboot.exption;

import jdk.nashorn.internal.objects.annotations.Constructor;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result {
// 响应业务状态
private Integer status;
// 响应消息
private String msg;

public static Result error(RuntimeException e) {
Result result = new Result();
result.setMsg(e.getMessage());
return result;
}

public static Result error(CodeMsg codeMsg) {
Result result = new Result();
result.setMsg(codeMsg.getMsg());
result.setStatus(codeMsg.getCode());
return result;
}
}

方法二:

Result.java
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
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Result<T> {
/** 状态码 */
private String code;

/** 提示信息 */
private String msg;

/** 响应数据 */
private T data;

/**
* 失败
*/
public static Result error(BaseErrorInfo errorInfo) {
Result rb = new Result();
rb.setCode(errorInfo.getResultCode());
rb.setMsg(errorInfo.getGetResultMsg());
rb.setData(null);
return rb;
}

/**
* 失败
*/
public static Result error(String code, String message) {
Result rb = new Result();
rb.setCode(code);
rb.setMsg(message);
rb.setData(null);
return rb;
}

}
BaseErrorInfoInterface.java
1
2
3
4
5
6
7
8
9
10
public interface BaseErrorInfo {
/**
* 状态码
*/
String getResultCode();
/**
* 错误信息
*/
String getGetResultMsg();
}
CommonEnum.java
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
public enum CommonEnum implements BaseErrorInfo{

// 数据操作错误定义
SUCCESS("200","成功"),
RUNTIME_ERROR("5001", "自定义的错误"),
NO_KNOW_ERROR("5002", "未知的异常信息")
;

/** 错误码 */
private String resultCode;
/** 错误描述 */
private String resultMsg;

CommonEnum(String resultCode, String resultMsg) {
this.resultCode = resultCode;
this.resultMsg = resultMsg;
}

@Override
public String getResultCode() {
return resultCode;
}

@Override
public String getGetResultMsg() {
return resultMsg;
}
}

BizException.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class BizException extends RuntimeException{

private String errorCode;
private String errorMsg;

public BizException() {
}

public BizException(BaseErrorInfo errorInfoInterface) {
super(errorInfoInterface.getResultCode());
this.errorCode = errorInfoInterface.getResultCode();
this.errorMsg = errorInfoInterface.getGetResultMsg();
}

public BizException(String errorCode, String errorMsg) {
super(errorCode);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
}
GlobalExceptionHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@ControllerAdvice
public class GlobalException {

@ExceptionHandler(value = RuntimeException.class)
@ResponseBody
public Result runtimeException(RuntimeException e) {
return Result.error(CommonEnum.RUNTIME_ERROR);
}

/**
* 处理其他异常
*/
@ExceptionHandler(value =Exception.class)
@ResponseBody
public Result exceptionHandler(HttpServletRequest req, Exception e){
return Result.error(CommonEnum.NO_KNOW_ERROR); // 枚举类是BaseErrorInfo接口的具体子类,所以这里可以写接口实现类的参数
}

}

注: return Result.error(CommonEnum.NO_KNOW_ERROR); // 枚举类是BaseErrorInfo接口的具体子类,所以这里可以写接口实现类的参数

测试:
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
@RestController
public class TestController {
@Autowired
UserService userService;

@GetMapping("/error1")
public int error_test0() {
return 4/0;
}

@GetMapping("/error2")
public int error_test1() {
return userService.test11(11);
}

@GetMapping("/error3")
public int error_test2() {
if (true) {
throw new BizException("5004", "抛出的自定义异常");
}
return 1;
}

@GetMapping("/error4")
public int error_test3() {
if (true) {
throw new BizException("5005", "抛出的自定义异常11");
}
return 1;
}
}