在系统开发过程当中,总少难免要本身处理一些异常信息,而后将异常信息变成友好的提示返回到客户端的这样一个过程,以前都是new一个自定义的异常,固然这个所谓的自定义异常也是继承RuntimeException的,但这样每每会形成异常信息说明不一致的状况,因此就想到了用枚举来解决的办法。java
一、先建立一个接口,里面提供两个方法,一个是getErrorCode, 一个是getErrorMessage,如:this
public interface IErrorCode { public String getErrorCode(); public String getErrorMessage(); }
二、建立一个枚举,实现IErrorCode里的方法spa
public enum SysErrorEnums implements IErrorCode { /**参数为空*/ EMPTY_PARAME("A11002","参数为空"), /**参数错误*/ ERROR_PARAME("A11002","参数错误"); private String errorCode; private String errorMessage; private SysErrorEnums(String errorCode, String errorMessage) { this.errorCode = errorCode; this.errorMessage = errorMessage; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
三、定义一个自定义的异常类 code
public class BusinessException extends RuntimeException { private static final long serialVersionUID = 1L; private IErrorCode iErrorCode; private String errorCode; private String errorMessage; private Map<String, Object> errorData; public BusinessException(IErrorCode iErrorCode) { super(); this.iErrorCode = iErrorCode; this.errorCode = iErrorCode.getErrorCode(); this.errorMessage = iErrorCode.getErrorMessage(); } //其余get、set、构造方法 }
四、代码中抛异常blog
if(true){ throw new BusinessException(SysErrorEnums.EMPTY_OBJ); }
五、能够经过异常拦截器来拦截错误,获取错误后统一格式输出;继承
这样作的好处是能够高度统一全部异常返回的code及message, 若是须要更改提示信息或代号,只需更改SysErrorEnums便可,而且能够自行添加多个异常枚举文件来分别对应不一样的模板异常信息。代码结构简单,清淅。接口