专栏名称: ImportNew
伯乐在线旗下账号,专注Java技术分享,包括Java基础技术、进阶技能、架构设计和Java技术领域动态等。
目录
相关文章推荐
ImportNew  ·  亚马逊程序员破防:AI ... ·  17 小时前  
芋道源码  ·  面试官:为什么数据库连接很消耗资源? ·  15 小时前  
51好读  ›  专栏  ›  ImportNew

改进异常处理的 6 条建议

ImportNew  · 公众号  · Java  · 2017-12-25 12:00

正文

请到「今天看啥」查看全文



一个更好的办法是使用枚举表示异常类型。为每个错误分类创建一个枚举(付款、认证等),让枚举实现ErrorCode接口并作为异常的一个属性。


当抛出异常时,只要传入合适的枚举就可以了。


throw new SystemException(PaymentCode.CREDIT_CARD_EXPIRED);


现在如果需要测试异常只要比较异常代码和枚举就可以了。


catch (SystemException e) {

if (e.getErrorCode() == PaymentCode.CREDIT_CARD_EXPIRED) {

...

}

}


通过将错误码作为查找资源的key就可以方便地提供友好的国际化文本。


public class SystemExceptionExample3 {

public static void main(String[] args) {

System.out.println(getUserText(ValidationCode.VALUE_TOO_SHORT));

}

public static String getUserText(ErrorCode errorCode) {

if (errorCode == null) {

return null;

}

String key = errorCode.getClass().getSimpleName() + "__" + errorCode;

ResourceBundle bundle = ResourceBundle.getBundle("com.northconcepts.exception.example.exceptions");

return bundle.getString(key);

}

}


3. 为枚举添加错误值


在很多时候可以为异常添加错误值,比如HTTP返回值。这种情况下,可以在ErrorCode接口添加一个getNumber方法并在每个枚举中实现这个方法。







请到「今天看啥」查看全文