2015-07-20 69 views
0

我写这篇代码和PMD抱怨我可以实现更多优化来记录异常吗?

名称

私有方法无效xyzMethod(AnyObject anyObject)

位置

类XYZClass(xyz.package)

问题s ynopsis

正在对捕获到的异常执行实例检查。为此异常类型创建一个单独的catch子句。

try { 
     premium = serviceCallEjb(anfrage); 
    } catch (Exception e){ 
     final int typeError; 
     if(e instanceof ServiceException){ 
      typeError = CcaLogManager.ERROR; 
      e.printStackTrace(); 
     } else { 
      typeError = CcaLogManager.WARN; 
     } 
     myAnfrage.setStatus(DcAnfrage.ProcessingError); 
     myAnfrage.setStatusInfo(e.getMessage()); 
     final String message = String.format("Error in CcaMotorinsuranseCalculator, caught: %s, message: %s",e.getClass().getName(),e.getMessage()); 
     CcaLogManager.log(typeError, message); 
    } 

你喜欢,如果我把它写这样吗?

我可以做的任何其他优化?

try { 
     premium = serviceCallEjb(anfrage); 
    } 
    catch(ServiceException e){ 
     final int typeError; 
     typeError = CcaLogManager.ERROR; 
     e.printStackTrace(); 
     processException(e, typeError); 
    } 
    catch (Exception e){ 
     final int typeError; 
     typeError = CcaLogManager.WARN;    
     processException(e, typeError); 
    } 

private <T extends Exception> void processException(T e, final int typeError){ 
    this.myObject.setStatus(/*Any number*/7); 
    this.myObject.setStatusInfo(e.getMessage()); 
    final String message = String.format("Error in Some place, caught: %s, message: %s",e.getClass().getName(),e.getMessage()); 
    Logger.log(typeError, message); 
} 
+0

ServiceException是一个错误,任何其他异常是一个警告 –

回答

1

首先,我建议不要在任何生产代码中调用e.printStackTrace()。它将原始输出发送到进程的标准错误流,这在EJB应用程序中永远不会有用。无论如何,即使您最终打印到stderr,该逻辑也应驻留在异常处理代码中。当你消除,你的代码看起来是这样的:

try { 
    premium = serviceCallEjb(anfrage); 
} 
catch (Exception e){ 
    processException(e, e instanceof ServiceException? 
        CcaLogManager.ERROR : CcaLogManager.WARNING); 
} 

鉴于这种形式,它似乎连instanceof逻辑可能是processException的工作描述的一部分。这样,一个方法就可以捕获整个应用程序中所有的异常处理业务规则。

如果你唯一的目标是满足PMD,那么这将是一个干净的版本:

try { 
    premium = serviceCallEjb(anfrage); 
} 
catch (ServiceException e){ 
    processException(e, CcaLogManager.ERROR); 
} 
catch (Exception e){ 
    processException(e, CcaLogManager.WARNING); 
} 
+0

外观极好,谢谢 –