如何在传播结果或错误时调用 CompletableFuture 回调?

How to invoke CompletableFuture callback while propagating result or error?

我正在尝试 .exceptionally 和 .handle,但它们似乎不起作用。在 Scala 中,您可以在未来使用类似于 finally 块的闭包调用方法(它在异常和成功时运行)并且它按原样将异常或成功传播到链中。

我试过了...

    CompletableFuture<Object> future = newFuture.handle((r, e) -> {
        if(r != null)
            return r;
        else if(e != null)
            return e;
        else
            return new RuntimeException("Asdf");            
    });

    Assert.assertTrue(future.isCompletedExceptionally());

但该测试失败了,因为未来完全成功,结果是异常(多么奇怪)。

ohhhhh,我想我明白了....类似这样的东西似乎有效

    CompletableFuture<Integer> future2 = newFuture.handle((r, e) -> {

        //put finally like logic right here....

        if(r != null)
            return r;
        else if(e != null)
            throw new RuntimeException(e);
        else
            throw new RuntimeException("weird");
    });

使用CompletableFuture#whenComplete(BiConsumer)。它的 javadoc 状态

Returns a new CompletionStage with the same result or exception as this stage, that executes the given action when this stage completes.

When this stage is complete, the given action is invoked with the result (or null if none) and the exception (or null if none) of this stage as arguments. The returned stage is completed when the action returns. If the supplied action itself encounters an exception, then the returned stage exceptionally completes with this exception unless this stage also completed exceptionally.

换句话说,无论成功或失败,它都会被调用,并将传播初始未来的状态(除非 BiConsumer 抛出异常)。

CompletableFuture<String> future2 = newFuture.whenComplete((r, e) -> {
    // consume the result
});

如果您需要转换结果(在您的示例中,您不需要),那么您可以使用 handle 并自己传播内容。