成品
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; } }
步骤:
- 新建异常类,继承Exception 或 RuntimeException
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(); }
-
自定义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; } }