Springboot通用返回
不用spring的异常,抛出500很危险
通用返回类
public class Result<T> implements Serializable {
public final static int SUCCESS = 0;
public final static int FAILED = -1;
private final static String SUCCESS_MSG = "OK";
public static <T> Result<T> newSuccess(T result) {
return new Result<>(SUCCESS, result, SUCCESS_MSG);
}
public static <T> Result<T> newFailed(String msg) {
return new Result<>(FAILED, null, msg);
}
/**
* 返回码
*/
private int status;
/**
* 正确时的返回结果
*/
private T result;
/**
* 错误信息
*/
private String msg;
}
用范型解决结果的类型
统一有返回码,错误信息,以及res包含的data数据(json)
通用异常类
public class CommonException extends RuntimeException {
public static final int ERROR_CODE_DEFAULT = -1;
private final int status;
private final String msg;
public CommonException(int status, String msg) {
super(msg);
this.msg = msg;
this.status = status;
}
public CommonException(String msg) {
super(msg);
this.msg = msg;
this.status = ERROR_CODE_DEFAULT;
}
public CommonException(int status, String msg, Throwable cause) {
super(msg);
this.msg = msg;
this.status = status;
}
public int getStatus() {
return status;
}
public String getMsg() {
return msg;
}
}
继承运行时异常
springboot 捕捉自定义异常
@ControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler(Exception.class)
@ResponseBody
public Result<?> handleException(Throwable throwable) {
log.error("通用异常处理", throwable);
return Result.newFailed(throwable.getMessage());
}
}
使用切面编程捕捉异常,并调用通用返回类Result
网友评论