SpringBoot全局异常处理

1. 代码

  • 定义错误枚举
1
2
3
4
5
6
7
8
9
@AllArgsConstructor
@Getter
public enum ErrorCodeEnum {

SYSTEM_ERROR(100001, "系统异常");

private final Integer code;
private final String msg;
}
  • 定义异常类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 业务异常
*/
@Data
public class BizException extends RuntimeException {
private Integer code;
private String msg;

public BizException(ErrorCodeEnum errorCodeEnum) {
super(errorCodeEnum.getMsg());
this.code = errorCodeEnum.getCode();
this.msg = errorCodeEnum.getMsg();
}
}
  • 定义全局异常处理类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 全局异常处理
*/
@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(BizException.class)
public Result handleBizException(BizException bizException) {
return Result.fail(bizException.getCode(), bizException.getMsg());
}

@ExceptionHandler(Exception.class)
public Result handleException(Exception exception) {
return Result.fail(exception.getMessage());
}
}