为了不阻止执行,我需要动态组合(基于计算结果)CompletionStages
,最终我需要捕获操作期间可能出现的异常,以便仔细关闭执行。
我已经实现了以下类似内容:
public CompletableFuture<Data> getData() {
final Data accumulator = new Data();
CompletableFuture<Data> result = new CompletableFuture<>();
CompletableStage exec = ... //starting execution
exec.thenComposeAsync(
(res) -> process(accumulator, res)
).thenAccept(t -> result.complete(accumulator));
return result;
}
private CompletionStage<Void> process(Data acc, Result res) {
res.data().forEach(
currData -> {
add.addData(currData);
}
);
if (res.hasMoreData()) {
return res.fetchNextData().thenComposeAsync(
(nextData) -> process(acc, nextData)
);
}
return CompletableFuture.completedFuture(null);
}
我不知道这是否是实现该解决方案的最佳方法,但如果一切正常,它会起作用。由于任何原因在forEach
块中出现异常时,都会出现问题,该错误不会传播回getData
调用者,因此我无法使用exceptionally
方法捕获该错误,从而以安全的方式停止我的应用程序。我想我做错了。
当传递给thenComposeAsync
的函数异常失败时,thenComposeAsync
返回的将来将异常完成。这导致由链式常规操作创建的期货也异常完成,而不评估其功能。