自定义运行时异常设计(RuntimeException)

在每个公司的架构中,日志肯定是重点,以至于很多时候需要对日志进行优化!

那么该怎么设计,怎么定义自己想提示出的自定义消息呢,下面就是一个很好的设计示例,以供参考!


本文采取从上到下的模式用代码设计:


1. 自定义异常根类:

[java]  view plain  copy
  1. /** 
  2.  * 公司的运行时异常根类。【这个类可以打进jar包,供全公司使用】 
  3.  * 
  4.  * <p> 
  5.  * 统一异常层次,便于处理与监控。 
  6.  * 
  7.  * @author  
  8.  * 
  9.  */  
  10. public class CompanyRuntimeException extends RuntimeException {  
  11.     /** serialVersionUID */  
  12.     private static final long serialVersionUID = 0L;  
  13.   
  14.     /** 严重级别 */  
  15.     protected int severity = CompanyExceptionSeverity.NORMAL;  
  16.   
  17.     /** 
  18.      * 空构造器。 
  19.      */  
  20.     public CompanyRuntimeException() {  
  21.         super();  
  22.     }  
  23.   
  24.     /** 
  25.      * 构造器。 
  26.      * 
  27.      * @param severity 严重级别 
  28.      */  
  29.     public CompanyRuntimeException(int severity) {  
  30.         super();  
  31.   
  32.         this.severity = severity;  
  33.     }  
  34.   
  35.     /** 
  36.      * 构造器。 
  37.      * 
  38.      * @param message 消息 
  39.      */  
  40.     public CompanyRuntimeException(String message) {  
  41.         super(message);  
  42.     }  
  43.   
  44.     /** 
  45.      * 构造器。 
  46.      * 
  47.      * @param message 消息 
  48.      * @param severity 严重级别 
  49.      */  
  50.     public CompanyRuntimeException(String message, int severity) {  
  51.         super(message);  
  52.   
  53.         this.severity = severity;  
  54.     }  
  55.   
  56.     /** 
  57.      * 构造器。 
  58.      * 
  59.      * @param cause 原因 
  60.      */  
  61.     public CompanyRuntimeException(Throwable cause) {  
  62.         super(cause);  
  63.     }  
  64.   
  65.     /** 
  66.      * 构造器。 
  67.      * 
  68.      * @param cause 原因 
  69.      * @param severity 严重级别 
  70.      */  
  71.     public CompanyRuntimeException(Throwable cause, int severity) {  
  72.         super(cause);  
  73.   
  74.         this.severity = severity;  
  75.     }  
  76.   
  77.     /** 
  78.      * 构造器。 
  79.      * 
  80.      * @param message 消息 
  81.      * @param cause 原因 
  82.      */  
  83.     public CompanyRuntimeException(String message, Throwable cause) {  
  84.         super(message, cause);  
  85.     }  
  86.   
  87.     /** 
  88.      * 构造器。 
  89.      * 
  90.      * @param message 消息 
  91.      * @param cause 原因 
  92.      * @param severity 严重级别 
  93.      */  
  94.     public CompanyRuntimeException(String message, Throwable cause, int severity) {  
  95.         super(message, cause);  
  96.   
  97.         this.severity = severity;  
  98.     }  
  99.   
  100.     /** 
  101.      * @return Returns the severity. 
  102.      */  
  103.     public int getSeverity() {  
  104.         return severity;  
  105.     }  
  106.   
  107.     /** 
  108.      * @see java.lang.Throwable#toString() 
  109.      */  
  110.     public String toString() {  
  111.         StringBuffer buffer = new StringBuffer();  
  112.   
  113.         buffer.append(super.toString()).append(" - severity: ");  
  114.   
  115.         switch (severity) {  
  116.             case CompanyExceptionSeverity.MINOR:  
  117.                 buffer.append("MINOR");  
  118.                 break;  
  119.   
  120.             case CompanyExceptionSeverity.NORMAL:  
  121.                 buffer.append("NORMAL");  
  122.                 break;  
  123.   
  124.             case CompanyExceptionSeverity.MAJOR:  
  125.                 buffer.append("MAJOR");  
  126.                 break;  
  127.   
  128.             case CompanyExceptionSeverity.CRITICAL:  
  129.                 buffer.append("CRITICAL");  
  130.                 break;  
  131.   
  132.             default:  
  133.                 buffer.append("UNKNOWN");  
  134.         }  
  135.   
  136.         buffer.append("(").append(severity).append(")");  
  137.   
  138.         return buffer.toString();  
  139.     }  
  140. }  

异常级别分类:

[java]  view plain  copy
  1. /** 
  2.  * 异常严重级别常量。 
  3.  * 
  4.  * @author  
  5.  * 
  6.  * @version  
  7.  */  
  8. public interface CompanyExceptionSeverity {  
  9.     /** 轻微 */  
  10.     int MINOR = 1;  
  11.   
  12.     /** 一般 */  
  13.     int NORMAL = 2;  
  14.   
  15.     /** 重要 */  
  16.     int MAJOR = 3;  
  17.   
  18.     /** 严重 */  
  19.     int CRITICAL = 4;  
  20. }  


2. 每个业务的自定义异常类,例如MyPayException【自定义的测试业务】

[java]  view plain  copy
  1. /** 
  2.  * 自定义系统运行时异常 
  3.  * 
  4.  * @author  
  5.  * @version  
  6.  */  
  7. public class MyPayException extends CompanyRuntimeException {  
  8.   
  9.     /** serialVersionUID */  
  10.     private static final long      serialVersionUID = 0L;  
  11.   
  12.     /** 返回码 */  
  13.     private MyPayResultCodeEnum resultCode;  
  14.   
  15.     /** 
  16.      * 构造函数 
  17.      *  
  18.      * @param resultCode    返回码 
  19.      */  
  20.     public MyPayException(MyPayResultCodeEnum resultCode) {  
  21.         super();  
  22.         this.resultCode = resultCode;  
  23.     }  
  24.   
  25.     /** 
  26.      * 构造函数 
  27.      *  
  28.      * @param resultCode    返回码 
  29.      * @param e             需要传递的异常 
  30.      */  
  31.     public MyPayException(MyPayResultCodeEnum resultCode, Throwable e) {  
  32.         super(e);  
  33.         this.resultCode = resultCode;  
  34.     }  
  35.   
  36.     /** 
  37.      * 构造函数 
  38.      *  
  39.      * @param resultCode    返回码 
  40.      * @param message       错误信息 
  41.      */  
  42.     public MyPayException(MyPayResultCodeEnum resultCode, String message) {  
  43.         super(message);  
  44.         this.resultCode = resultCode;  
  45.     }  
  46.   
  47.     @Override  
  48.     public String toString() {//ToStringBuilder ToStringStyle所属于commons-lang jar包  
  49.         return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);  
  50.     }  
  51.   
  52.     /* 
  53.      * getter and setter 
  54.      */  
  55.     public MyPayResultCodeEnum getResultCode() {  
  56.         return resultCode;  
  57.     }  
  58.   
  59.     public void setResultCode(MyPayResultCodeEnum resultCode) {  
  60.         this.resultCode = resultCode;  
  61.     }  
  62.   
  63. }  

3.业务异常信息枚举

[java]  view plain  copy
  1. /** 
  2.  * 自定义业务操作返回码枚举 
  3.  * 
  4.  * @author  
  5.  * @version $ 
  6.  */  
  7. public enum MyPayResultCodeEnum {  
  8.   
  9.     /** 操作成功 */  
  10.     SUCCESS("SUCCESS""操作成功"),  
  11.   
  12.     /** 系统错误 */  
  13.     SYSTEM_FAILURE("SYSTEM_FAILURE""系统错误"),  
  14.   
  15.     /** 参数为空 */  
  16.     NULL_ARGUMENT("NULL_ARGUMENT""参数为空"),  
  17.   
  18.     /** 参数不正确 */  
  19.     ILLEGAL_ARGUMENT("ILLEGAL_ARGUMENT""参数不正确"),  
  20.   
  21.     /** 邮箱非法 */  
  22.     EMAIL_ILLEGAL("EMAIL_ILLEGAL""邮箱非法")  
  23.   
  24.     ;  
  25.     /** 枚举值 */  
  26.     private String value;  
  27.   
  28.     /** 枚举信息 */  
  29.     private String message;  
  30.   
  31.     private MyPayResultCodeEnum(String value, String message) {  
  32.         this.value = value;  
  33.         this.message = message;  
  34.     }  
  35.   
  36.     /** 
  37.      * 根据枚举值获取枚举对象,如果找不到对应的枚举返回<code>null</code> 
  38.      * 
  39.      * @param value 枚举值 
  40.      * @return 枚举对象 
  41.      */  
  42.     public static MyPayResultCodeEnum getEnumByValue(String value) {  
  43.         for (MyPayResultCodeEnum resultCode : MyPayResultCodeEnum.values()) {  
  44.             if (resultCode.getValue().equals(value)) {  
  45.                 return resultCode;  
  46.             }  
  47.         }  
  48.         return null;  
  49.     }  
  50.   
  51.     /* 
  52.      * getter 
  53.      */  
  54.     public String getValue() {  
  55.         return value;  
  56.     }  
  57.   
  58.     public String getMessage() {  
  59.         return message;  
  60.     }  
  61.   
  62. }  


4.业务执行捕获异常

[java]  view plain  copy
  1. public <T> T execute(){  
  2.         MyPayResult retResult = new MyPayResult();  
  3.         try {  
  4.             // 1.业务校验  
  5.             // 2.业务执行  
  6.             // 3.异常处理  
  7.         } catch (MyPayException e) {  
  8.             retResult.setSuccess(false);  
  9.             retResult.setResultCode(e.getResultCode());  
  10.             retResult.setMessage(StringUtil.isNotBlank(e.getMessage()) ? e.getMessage() : e  
  11.                 .getResultCode().getMessage());  
  12.             logger.warn("业务异常," + e.getResultCode().getMessage(), e);  
  13.         }  
  14.           
  15.         return (T)retResult;  
  16.     }  

5.第4中的返回值定义,以供调用端判断是否执行成功还是失败:

[java]  view plain  copy
  1. import java.io.Serializable;  
  2.   
  3.   
  4. /** 
  5.  * 订购中心业务处理结果 
  6.  * 
  7.  * @author  
  8.  * @version  
  9.  */  
  10. public class MyPayResult implements Serializable {  
  11.   
  12.     /** serialVersionUID */  
  13.     private static final long      serialVersionUID = 1L;  
  14.   
  15.     /** 成功标志 */  
  16.     protected boolean              success;  
  17.   
  18.     /** 返回码 */  
  19.     private MyPayResultCodeEnum resultCode;  
  20.   
  21.     /** 返回信息 */  
  22.     protected String               message;  
  23.   
  24.     /** 
  25.      * 构造函数,默认返回码为“SUCCESS”。 
  26.      */  
  27.     public MyPayResult() {  
  28.         resultCode = MyPayResultCodeEnum.SUCCESS;  
  29.         this.message = resultCode.getMessage();  
  30.         success = true;  
  31.     }  
  32.   
  33.     /** 
  34.      * 构造函数 
  35.      *  
  36.      * @param success 成功标志 
  37.      */  
  38.     public MyPayResult(boolean success) {  
  39.         this.success = success;  
  40.         this.resultCode = MyPayResultCodeEnum.SYSTEM_FAILURE;  
  41.         this.message = resultCode.getMessage();  
  42.     }  
  43.   
  44.     /** 
  45.      * 构造函数 
  46.      *  
  47.      * @param resultCode 返回码 
  48.      */  
  49.     public MyPayResult(MyPayResultCodeEnum resultCode) {  
  50.         success = resultCode == MyPayResultCodeEnum.SUCCESS;  
  51.         this.resultCode = resultCode;  
  52.         this.message = resultCode.getMessage();  
  53.     }  
  54.   
  55.     /** 
  56.      * 构造函数 
  57.      *  
  58.      * @param resultCode 返回码 
  59.      */  
  60.     public MyPayResult(boolean success, MyPayResultCodeEnum resultCode) {  
  61.         this.success = success;  
  62.         this.resultCode = resultCode;  
  63.         this.message = resultCode.getMessage();  
  64.     }  
  65.   
  66.     /** 
  67.      * 返回结果信息 
  68.      * 
  69.      * @return 如果resultCode存在,返回resultCode的message,否则返回result中的message字段 
  70.      */  
  71.     public String findMessage() {  
  72.         return StringUtil.isNotBlank(message) ? message : resultCode.getMessage();  
  73.     }  
  74.   
  75.     /* 
  76.      * getters and setters 
  77.      */  
  78.   
  79.     /** 
  80.      * Getter method for property <tt>success</tt>. 
  81.      *  
  82.      * @return property value of success 
  83.      */  
  84.     public boolean isSuccess() {  
  85.         return success;  
  86.     }  
  87.   
  88.     /** 
  89.      * Setter method for property <tt>success</tt>. 
  90.      *  
  91.      * @param success value to be assigned to property success 
  92.      */  
  93.     public void setSuccess(boolean success) {  
  94.         this.success = success;  
  95.     }  
  96.   
  97.     /** 
  98.      * Getter method for property <tt>resultCode</tt>. 
  99.      *  
  100.      * @return property value of resultCode 
  101.      */  
  102.     public MyPayResultCodeEnum getResultCode() {  
  103.         return resultCode;  
  104.     }  
  105.   
  106.     /** 
  107.      * Setter method for property <tt>resultCode</tt>. 
  108.      *  
  109.      * @param resultCode value to be assigned to property resultCode 
  110.      */  
  111.     public void setResultCode(MyPayResultCodeEnum resultCode) {  
  112.         this.resultCode = resultCode;  
  113.     }  
  114.   
  115.     /** 
  116.      * Getter method for property <tt>message</tt>. 
  117.      *  
  118.      * @return property value of message 
  119.      */  
  120.     public String getMessage() {  
  121.         return message;  
  122.     }  
  123.   
  124.     /** 
  125.      * Setter method for property <tt>message</tt>. 
  126.      *  
  127.      * @param message value to be assigned to property message 
  128.      */  
  129.     public void setMessage(String message) {  
  130.         this.message = message;  
  131.     }  
  132.   
  133.     /**  
  134.      * @see java.lang.Object#toString() 
  135.      */  
  136.     @Override  
  137.     public String toString() {  
  138.         return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);  
  139.     }  
  140.       
  141. }  


6.使用范例:校验邮箱是否合法(可以放到工具类util)

[java]  view plain  copy
  1. /** Email验证正则表达式 */  
  2.     private static final String REGEX_EMAIL = "^(([_\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([_\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?))$";  
  3.   
  4. /** 
  5.      * 验证邮件地址格式 
  6.      * 
  7.      * @param email                 字符串 
  8.      * @param message               错误信息 
  9.      * @exception MyPayException 如果邮件格式不正确 
  10.      */  
  11.     public static void notEmail(String email, String message) {  
  12.         if (!StringUtil.isEmpty(email) && !Pattern.compile(REGEX_EMAIL).matcher(email).find()) {  
  13.             throw new MyPayException(MyPayResultCodeEnum.EMAIL_ILLEGAL, message);  
  14.         }  
  15.     }  



以上,设计有需要改进的地方,欢迎探讨!!!!

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值