什么是java CompletableFuture 相当于scala Future rescue and handle

What is java CompletableFuture equivalent of scala Future rescue and handle

我看到 CompletableFuture 有一个方法 handle 与 scala Future 的方法相同 handle 基本上将成功和异常都转换为成功成为 mapflatMap 上游(或 java 世界中的 thenApplythenCompose)。

Twitter 的未来 rescue(或 scala 的未来 recoverWith)在 java 中的等价物是什么?

scala 中的

rescue 基本上就像旧的 java try....catch,然后重新抛出更多信息以便更好地使用。例如在 twitterFuture.handlescalaFuture.recover 中 return 单位是 U 所以你 return 一个回应。在 twitterFuture.rescuescalaFuture.recoverWith 中,它 returns Future[U] 因此可以采取某些例外情况,添加更多信息和 return Future.exception(xxxxx)

对于 recover,如果您不需要 return 超类并且想要吞并所有异常,您可以只使用 exceptionally:

CompletableFuture<T> future = ...;
CompletableFuture<T> newFuture = future.exceptionally(_exc -> defaultValue);

否则需要用handle to get a CompletableFuture<CompletableFuture<U>>, and then use thenCompose收起:

CompletableFuture<T> future = ...;
CompletableFuture<T> newFuture = future.handle((v, e) -> {
        if (e == null) {
            return CompletableFuture.completedFuture(v);
        } else {
            // the real recoverWith part
            return applyFutureOnTheException(e);
        }
    }).thenCompose(Function.identity());