【问题标题】:How can I count the number of caught exceptions in Java batch process?如何计算 Java 批处理中捕获的异常数量?
【发布时间】: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 应该在方法内,以便在此方法内保持计数错误,并且此方法还调用其他methodBmethodC 等方法(在其他类中)。问题是,如果我想在捕获所有应用程序中发生的任何异常时增加 errors 变量,我必须将 errors 放入每个方法调用中。

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

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

【问题讨论】:

    标签: java spring exception


    【解决方案1】:

    为什么需要在 methodB 中使用 try catch 块而不是使用 throw Exception 方法签名

    public void methodA(int param1, int param2) throws Exception{
       methodB();
    }
    
    public void methodB() throws Exception{
       
         //code here
       
    }
    

    因为您正在调用方法中捕获异常,所以应该具有主要的错误计数逻辑。不在多个地方

     try{
          //My code goes here
          methodA(param1,param2);
       } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            errors++;
       }
    
       if (errors > 0 ) {
         log.error(errors + " error(s) ocurred in the application");
      }
    

    【讨论】:

    • 对不起,我一点都不清楚。我已经更新了我的问题,以便更好地解释它。但我这样做是因为我有一些方法应该返回一个默认值(例如 methodC 中的空字符串),但也会增加错误变量。
    【解决方案2】:

    如果您想在每个 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 2015-09-10
      • 2011-10-27
      • 2018-03-07
      • 2017-11-25
      相关资源
      最近更新 更多