自定義異常類

朝聖之路發表於2019-04-13

  成品

public class WebsiteException extends RuntimeException{

    private String resultCode;

    private String resultMsg;

    public WebsiteException(String resultCode, String resultMsg) {
        super(resultCode);
        this.resultCode = resultCode;
        this.resultMsg = resultMsg;
    }

    public WebsiteException(WebsiteCodeEnum codeEnum) {
        super(codeEnum.getCode());
        this.resultCode = codeEnum.getCode();
        this.resultMsg = codeEnum.getDesc();
    }

    public String getResultCode() {
        return resultCode;
    }

    public void setResultCode(String resultCode) {
        this.resultCode = resultCode;
    }

    public String getResultMsg() {
        return resultMsg;
    }

    public void setResultMsg(String resultMsg) {
        this.resultMsg = resultMsg;
    }
}

  步驟:

  1. 新建異常類,繼承Exception 或 RuntimeException
    public class WebsiteException extends RuntimeException{
    
        private String resultCode;
    
        private String resultMsg;
    
    }
  2. 根據需要新增構造(建議)
        public WebsiteException(String resultCode, String resultMsg) {
            super(resultCode);//呼叫父類構造,用於列印自定義錯誤資訊
            this.resultCode = resultCode;
            this.resultMsg = resultMsg;
        }
    
        public WebsiteException(WebsiteCodeEnum codeEnum) {
            super(codeEnum.getCode());//呼叫父類構造,用於列印自定義錯誤資訊
            this.resultCode = codeEnum.getCode();
            this.resultMsg = codeEnum.getDesc();
        }
  3. 自定義Enum(養成好習慣)

    public enum WebsiteCodeEnum {
    
        SYSTEM_ERROR("SYSTEM_ERROR", "系統異常");
    
        private String code;
    
        private String desc;
    
        WebsiteCodeEnum() {
        }
    
        WebsiteCodeEnum(String code, String desc) {
            this.code = code;
            this.desc = desc;
        }
    
        public String getCode() {
            return code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        public String getDesc() {
            return desc;
        }
    
        public void setDesc(String desc) {
            this.desc = desc;
        }
    }

相關文章