java - 如何计算 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
应该在方法内,以便在此方法内保持计数错误,并且此方法还调用其他方法,例如methodB
和methodC
(在其他类中)。问题是,errors
如果我想errors
在捕获所有应用程序中发生的任何异常时增加变量,我必须将其放入每个方法调用中。
有没有更好的方法来完成对 Java 应用程序中所有捕获的异常的计数?
顺便说一句,我正在使用 Spring Batch 2.2.6
解决方案
如果您想在每个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
推荐阅读
- r - 为什么 Tesseract 的边界框未在图像文本上对齐?
- javascript - 将 HTML 中文本内容的 JS 动画导出为动画 gif 或 PowerPoint 可导入画布对象
- python - Python延迟参数初始化奇怪的执行顺序
- powershell - 使用 PowerShell 检查 Power BI 文件是否损坏
- c# - 将位置 URI 指向另一个控制器
- javascript - 我将如何在节点 js 中加载 ogg 文件
- javascript - 使用 fs.append 写入 json 文件
- retrofit2 - java.net.SocketException:带有改造 POST 调用的管道损坏
- php - CakePHP 3 - 从数据库表显示日期到编辑表单帮助页面
- shell - 如何执行另一个命令的输出