後端統一異常處理

異常處理是對Exception的統一管理,當程序出現問題會將出錯信息打印出來,但是很多時候我們得到的是很多的堆棧信息和部分可以直接進行判斷的信息,通過自定義的封裝可以對異常信息進行統一管理,返回我們可以判斷的異常信息。

定義CommonError接口

package com.miaoshaproject.error;/*

public interface CommonError {
    public int getErrCode();
    public String getErrMsg();
    public CommonError setErrMsg(String errMsg);
}

定義枚舉類EmBusinessError

package com.miaoshaproject.error;/*

public enum  EmBusinessError implements CommonError{
    USER_NOT_EXIST(10001,"用戶不存在"),
    UNKNOWN_ERROR(10002,"未知錯誤"),
    PARAMETER_VALIDATION_ERROR(20001,"參數不合法"),
    USER_LOGIN_FAIL(20002,"用戶手機號或密碼不正確"),
    USER_NOT_LOGIN(20003,"用戶還未登陸"),
    //30000開頭爲交易信息錯誤定義
    STOCK_NOT_ENOUGH(30001,"庫存不足"),
    ;
    private EmBusinessError(int errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }
    private int errCode;
    private String errMsg;
    @Override
    public int getErrCode() {
        return this.errCode;
    }
    @Override
    public String getErrMsg() {
        return this.errMsg;
    }
    @Override
    public CommonError setErrMsg(String errMsg) {
        this.errMsg=errMsg;
        return this;
    }
}

定義異常處理類BusinessException

package com.miaoshaproject.error;/*

public class BusinessException extends Exception implements CommonError{
    private CommonError commonError;
    public BusinessException(CommonError commonError) {
        super();
        this.commonError = commonError;
    }
    public BusinessException(CommonError commonError,String errMsg){
        super();
        this.commonError = commonError;
        this.commonError.setErrMsg(errMsg);
    }
    public CommonError getCommonError(){
        return commonError;
    }
    @Override
    public int getErrCode() {
        return this.commonError.getErrCode();
    }
    @Override
    public String getErrMsg() {
        return this.commonError.getErrMsg();
    }
    @Override
    public CommonError setErrMsg(String errMsg) {
        this.commonError.setErrMsg(errMsg);
        return this;
    }
}

使用

返回具體結果:

 if (result.isHasErrors() ) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,result.getErrMsg());
        }

自定義返回值:

    throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "手機號已重複註冊");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章