Comboine CompletableStage动态地传播并最终传播错误

问题描述 投票:0回答:1

为了不阻止执行,我需要动态组合(基于计算结果)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方法捕获该错误,从而以安全的方式停止我的应用程序。我想我做错了。

java completable-future
1个回答
2
投票

当传递给thenComposeAsync的函数异常失败时,thenComposeAsync返回的将来将异常完成。这导致由链式常规操作创建的期货也异常完成,而不评估其功能。

© www.soinside.com 2019 - 2024. All rights reserved.