java - 在 Java 中处理 CompletableFuture 中的错误的方法
问题描述
我正在使用CompletableFuture
,我遇到了以下用例:
public void someFunction () {
CompletableFuture.runAsync(() -> computations())
.exceptionally((err) -> {
log.info(err + "");
return null;
});
}
public void computations() {
list.stream.forEach(() -> otherFunction());
}
public void otherFunction() {
//computations which can throw some error
}
正如你在这里看到的,我可以很容易地log
在exceptionally
块中出错,但是如果我不希望我的程序停止并继续直到list
迭代所有元素怎么办。如果有任何错误,我想记录错误并继续下一个而不是停止应用程序。
解决方案
您可以尝试捕获可以抛出异常的代码,如下所示:直接为每个项目处理异常而不阻塞 forEach 循环
public void otherFunction() {
try {
//computations which can throw some error
} catch (Exception e) {
// Log and handle error without blocking analysis for following items
}
}
如果您已经知道 otherFunction 可以抛出什么异常,则可以仅显式捕获该异常,并将异常保留为系统来处理其他异常。
推荐阅读
- excel - 如何向我的 VBA 代码添加另一个过滤器?
- ios - 如何以编程方式获得许可。拒绝 PhotoLibrary 授权
- javascript - 如何使占位符文本出现而不是值文本
- php - 更改 DOM 中的用户代理
- c++ - 这个正则表达式的括号以什么方式“不匹配”?
- mysql - 可以使用 SELECT 查询,但不能使用它来创建新表
- python - 如何从 python 中的 Dropbox 对象中获取姓名、姓氏和电子邮件?
- javascript - Javascript 干扰第二个 SVG 线动画
- sql - 如何通过查看过去的签到时间来区分白天和夜班?
- html - 如何创建不同级别的置顶标题?