在传播结果或错误时如何调用CompletableFuture回调? [英] How to invoke CompletableFuture callback while propagating result or error?

查看:85
本文介绍了在传播结果或错误时如何调用CompletableFuture回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试.exception和.handle,但是那些似乎不起作用.在scala中,您可以在将来使用闭包调用方法,就像close块一样(它在出现异常并成功运行时运行),并按原样在链上传播异常或成功.

I was trying .exceptionally and .handle but those don't seem to work. In scala, you can call a method on the future with a closure that is just like a finally block(it runs on exception AND on success) AND it propogates the exception or success up the chain as-is.

我尝试过了...

    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());

但是由于异常(多么奇怪)的结果,该测试由于将来完全成功而失败.

but that test fails as the future completely successfully with a result of exception(how weird).

推荐答案

使用

Use CompletableFuture#whenComplete(BiConsumer). Its javadoc states

返回与结果或异常相同的新 CompletionStage 此阶段,该阶段完成后执行给定的动作.

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

此阶段完成后,将使用结果(如果没有则为 null )和此异常(如果没有则为 null )舞台作为争论.动作完成后返回阶段返回.如果提供的操作本身遇到异常,则除非出现异常,否则返回的阶段将特别完成.这个阶段也异常完成.

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 引发异常).

In other words, it will be invoked regardless of success or failure and will propagate the initial future's state (unless the BiConsumer throws an exception).

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

如果您需要转换结果(在您的示例中不需要),则可以使用 handle 并自行传播.

If you needed to transform the result (in your example, you don't), then you could use handle and propagate things yourself.

这篇关于在传播结果或错误时如何调用CompletableFuture回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆