在系統開發過程中,總少不免要自己處理一些異常信息,然后將異常信息變成友好的提示返回到客戶端的這樣一個過程,之前都是new一個自定義的異常,當然這個所謂的自定義異常也是繼承RuntimeException的,但這樣往往會造成異常信息說明不一致的情況,所以就想到了用枚舉來解決的辦法。
1、先創建一個接口,里面提供兩個方法,一個是getErrorCode, 一個是getErrorMessage,如:
public interface IErrorCode {
public String getErrorCode();
public String getErrorMessage();
}
2、創建一個枚舉,實現IErrorCode里的方法
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; } }
3、定義一個自定義的異常類
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、構造方法 }
4、代碼中拋異常
if(true){ throw new BusinessException(SysErrorEnums.EMPTY_OBJ); }
5、可以通過異常攔截器來攔截錯誤,獲取錯誤后統一格式輸出;
這樣做的好處是可以高度統一所有異常返回的code及message, 如果需要更改提示信息或代號,只需更改SysErrorEnums即可,並且可以自行添加多個異常枚舉文件來分別對應不同的模板異常信息。代碼結構簡單,清淅。
