统计返回信息工具类

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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值