Spring boot 通过AOP思想,使用注解@RestControllerAdvice将异常统一到一个地方进行处理,这样可以避免代码中到处捕获和处理异常,让代码保持干净整洁。
简单对象的创建
首先创建一个枚举类型,用来保存各种返回状态
public enum ResultCode {
SUCCESS(200, "成功"),
PARAM_INVALID(401, "参数无效"),
TASK_NULL(404, "任务不存在"),
...
private int code;
private String msg;
ResultCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
然后再有一个统一的controller返回对象类:
public class ResultJson<T> implements Serializable{
private static final long serialVersionUID = 783015033603078674L;
private int code;
private String msg;
private T data;
public ResultJson (ResultCode resultCode,T data) {
setResultCode(resultCode);
this.data = data;
}
public static ResultJson success() {
ResultJson resultJson = new ResultJson();
resultJson.setResultCode(ResultCode.SUCCESS);
return resultJson;
}
public static <T> ResultJson success(T data){
return new ResultJson(ResultCode.SUCCESS, data);
}
public static ResultJson failure(ResultCode resultCode){
ResultJson resultJson = new ResultJson();
resultJson.setResultCode(resultCode);
return resultJson;
}
public void setResultCode(ResultCode resultCode) {
this.code = resultCode.getCode();
this.msg = resultCode.getMsg();
}
...省略构造方法和getter和setter方法;
}
自定义异常类:
public class CustomException extends RuntimeException {
private static final long serialVersionUID = 2984474148327146104L;
private ResultCode resultCode;
public CustomException(ResultCode resultCode) {
this.resultCode = resultCode;
}
...省略getter和setter方法;
}
然后就是创建一个统一异常处理的类了
@RestControllerAdvice
public class DefaultExceptionHandler {
private Logger logger = LoggerFactory.getLogger(DefaultExceptionHandler.class);
/**
* 处理所有自定义异常
* @param e
* @return
*/
@ExceptionHandler(CustomException.class)
public ResultJson handleCustomException(CustomException e){
return ResultJson.failure(e.getResultCode());
}
...这里可以增加其他想处理的异常
/**
* 处理所有异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
public ResultJson handleException(Exception e){
logger.error(e.getMessage());
return ResultJson.failure(ResultCode.SERVER_ERROR);
}
}
该类会拦截controller转发的请求过程中产生的异常,只要在异常处理类中定义的异常都可以被捕获处理,并返回给controller调用者。
业务方法中就可以不用去处理异常了。异常都集中到一处处理,修改也方便,而且所有定义的异常都能按照格式返回到前台。