【发布时间】:2021-03-07 23:11:58
【问题描述】:
我有一个 Java 批处理进程,它应该在进程结束时打印 Java 应用程序中捕获的异常数量。
这是强制性的,因为客户需要它。
我找到了解决方案,但似乎可以优化。
首先我创建了一个 int 变量来计算所有捕获的错误。
int errors = 0;
然后,我放置了一个 try/catch 块来捕获应用程序内部发生的每个异常:
try{
//My code goes here
methodA(param1,param2,errors);
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
errors++;
}
if (errors > 0 ) {
log.error(errors + " error(s) occurred in the application");
}
这是methodA、methodB和methodC:
public void methodA(int param1, int param2, int errors){
methodB(errors);
}
public void methodB(int errors){
try{
// using methodC result to do some other operations
String text1 = methodC(errors);
// more code here
}catch(Exception e){
//another code here
errors++;
}
}
public int methodC(int errors){
try{
//Calculate a String in textReturned variable
return textReturned;
}catch(Exception e){
//another code here
errors++;
return "";
}
}
直到这里一切正常,但正如您在 try 块内看到的那样,我调用 methodA(param1,param2, errors) 和 errors 应该在方法内,以便在此方法内保持计数错误,并且此方法还调用其他methodB 和 methodC 等方法(在其他类中)。问题是,如果我想在捕获所有应用程序中发生的任何异常时增加 errors 变量,我必须将 errors 放入每个方法调用中。
有没有更好的方法来完成对 Java 应用程序中所有捕获的异常的计数?
顺便说一句,我正在使用 Spring Batch 2.2.6
【问题讨论】: