背景
在实际业务中, 我们需要错误数据进行格式封装返回给前端, 以下例子使用标准 HTTP 状态码 + 错误信息码 + 错误信息的格式.
错误枚举类
首先需要定义一个错误枚举类, 来保存错误的基本信息.
@Getter
@AllArgsConstructor
public enum ErrorCodeMessageEnum {
SESSION_ERROR(10000, "Session 错误"),
JWT_ERROR(10001, "JWT 错误");
private int code;
private String message;
}
使用方法
ErrorCodeMessageEnum.SESSION_ERROR.getCode();
ErrorCodeMessageEnum.SESSION_ERROR.getMessage();
错误异常类
我们也可以定义一个异常类, 用来表示一种特定的异常.
@Getter
public class LogicException extends RuntimeException {
private static final long serialVersionUID = 1L;
private Integer code;
public LogicException(ErrorEnum errorEnum) {
super(errorEnum.getMessage());
this.code = errorEnum.getCode();
}
}
使用方法
new LogicException(ErrorCodeMessageEnum.SESSION_ERROR);
错误返回格式类
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ExceptionResponse {
private String code;
private String msg;
}
全局拦截类
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(LogicException.class)
public final ResponseEntity<ExceptionResponse> handleLogicException(LogicException ex, WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(ex.getCode(), ex.getMessage());
return new ResponseEntity<>(exceptionResponse, HttpStatus.BAD_REQUEST);
}
}