前言
在做web应用时候,请求处理过程中发生错误是非常常见情况。如果程序中每次都是通过try/catch进行异常处理,代码逻辑会变得非常乱
- 定义错误码的Code类
public enum Code implements Serializable {
BASE_SUCCESS(0),
SUCCESS(200),
ParamsError(403),
ParamsNull(120),
Exception(206),
ERROR(500),
BASE_ERROR(-1);
public int code;
public int getCode() {
return this.code;
}
public void setCode(int code) {
this.code = code;
}
private Code(int code) {
this.code = code;
}
}
- 定义返回的Result类
@Data
@Accessors(chain = true)
public class Result implements Serializable {
private static final long serialVersionUID = 7154887528070131284L;
private String message;
private Integer code;
private Boolean success;
private T data;
private Long timestamp;
private String sessionId;
public Result() {
timestamp = System.currentTimeMillis();
}
public static Result ofError(String msg, Integer code) {
return of(msg, code, null, false);
}
public static Result ofError(String msg) {
return of(msg, Code.ERROR.code, null, false);
}
public static Result ofError(String msg, String sessionId) {
return of(msg, Code.ERROR.code, null, false, sessionId);
}
public static Result ofSuccess(T data) {
return of(null, Code.SUCCESS.code, data, true);
}
public static Result
- controller层
@RequestMapping("/hello")
public String hello() throws Exception {
throw new BizException("发生错误");
}
- 自定义Exception
@Data
public class BizException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String message;
private int code = 500;
public BizException(String message) {
super(message);
this.message = message;
}
public BizException(String message, Throwable e) {
super(message, e);
this.message = message;
}
public BizException(String message, int code) {
super(message);
this.message = message;
this.code = code;
}
public BizException(String message, int code, Throwable e) {
super(message, e);
this.message = message;
this.code = code;
}
}
- 全局异常捕获(RestControllerAdvice)
@RestControllerAdvice
public class BizExceptionHandler {
@ExceptionHandler(BizException.class)
public Result RRExceptionHandler(BizException e) {
return Result.ofError(e.getMessage(), e.getCode());
}
}