首页 > 解决方案 > 如何计算 Java 批处理中捕获的异常数量?

问题描述

我有一个 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应该在方法内,以便在此方法内保持计数错误,并且此方法还调用其他方法,例如methodBmethodC(在其他类中)。问题是,errors如果我想errors在捕获所有应用程序中发生的任何异常时增加变量,我必须将其放入每个方法调用中。

有没有更好的方法来完成对 Java 应用程序中所有捕获的异常的计数?

顺便说一句,我正在使用 Spring Batch 2.2.6

标签: javaspringexception

解决方案


如果您想在每个catch块中增加一个计数器,我相信您可以使用面向方面的编程,特别是 AspectJ 的handler切入点来做到这一点。

Spring 的 AOP 不提供handler切入点,但 Spring 确实与 AspectJ 集成。

请参阅:https ://docs.spring.io/spring-framework/docs/5.3.4/reference/html/core.html#aop-using-aspectj


推荐阅读