java自定義異常(列舉)
阿新 • • 發佈:2018-12-17
public class SimpleException extends RuntimeException { private String msg ; private StatusCode statusCode ; public SimpleException(StatusCode statusCode, String msg) { super(msg) ; this.msg = msg ; this.statusCode = statusCode ; } public SimpleException(StatusCode statusCode, String msg, Throwable e) { super(msg, e) ; this.msg = msg ; this.statusCode = statusCode ; } public StatusCode getStatusCode() { return statusCode; } public void setStatusCode(StatusCode statusCode) { this.statusCode = statusCode; } @Override public String toString() { return "登陸異常:"+this.statusCode+" "+this.msg ; } }
public enum StatusCode { UNKNOWN_ERR("未知錯誤",0), USERNAME_OR_PASSWORD_ERR("使用者名稱密碼錯誤", 1), REANLNAME_OR_IDNUMBER_ERR("姓名身份證號錯誤", 2), SMS_CODE_ERR("驗證碼錯誤", 3), REDIS_ERR("Redis操作異常",4), GENERAL_ERR("一般異常",5), HTTP_POST_ERR("http post 請求異常",6), HTTP_GET_ERR("http get 請求異常",7); // 成員變數 private String name; private Integer index; // 構造方法 private StatusCode(String name, Integer index) { this.name = name; this.index = index; } // 普通方法 public static String getName(Integer index) { for (StatusCode c : StatusCode.values()) { if (c.getIndex() == index) { return c.name; } } return null; } // get set 方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getIndex() { return index; } public void setIndex(Integer index) { this.index = index; } @Override public String toString() { return this.index+":"+this.name; } }