1.异常信息枚举类:
public enum AppExceptionCodeMsg {
INVALID_CODE(10000,"验证码无效"),
USERNAME_NOT_EXISTS(10001,"用户名不存在"),
USER_CREDIT_NOTENOUTH(10002,"用户积分不足");
private int code;
private String msg;
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
AppExceptionCodeMsg(int code, String msg) {
this.code = code;
this.msg = msg;
}
}
2.自定义异常类
public class AppException extends RuntimeException{
private int code = 500;
private String msg = "服务器异常";
public AppException(AppExceptionCodeMsg appExceptionCodeMsg){
super();
this.code = appExceptionCodeMsg.getCode();
this.msg = appExceptionCodeMsg.getMsg();
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
3.统一异常处理
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = {Exception.class})
@ResponseBody
public <T> Resp<T> exceptionHandler(Exception e){
//这里先判断拦截到的Exception是不是自定义的异常类
if(e instanceof AppException){
AppException appException = (AppException) e;
return Resp.error(appException.getCode(),appException.getMsg());
}
//如果拦截的异常不是自定义的(如:数据库主键冲突)
return Resp.error(500,"服务器端异常");
}
}
5.统一信息返回
public class Resp<T> {
//服务端返回的错误代码
private int code;
//服务端返回的错误信息
private String msg = "success";
//服务端返回的数据
private T data;
private Resp(int code,String msg,T data){
this.code = code;
this.msg = msg;
this.data = data;
}
public static <T> Resp success(){
Resp resp = new Resp(200,null,null);
return resp;
}
public static <T> Resp success(String msg,T data){
Resp resp = new Resp(200,msg,data);
return resp;
}
public static <T> Resp error(AppExceptionCodeMsg appExceptionCodeMsg){
Resp resp = new Resp(appExceptionCodeMsg.getCode(),appExceptionCodeMsg.getMsg(),null);
return resp;
}
public static <T> Resp error(int code,String msg){
return new Resp(code,msg,null);
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
public T getData() {
return data;
}
}