使用CompletableFuture检查异常 [英] Checked exception with CompletableFuture

查看:1545
本文介绍了使用CompletableFuture检查异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Java 8 很棒的功能CompletableFuture,我想使用此新功能的例外转换旧的异步代码。但是经过检查的例外情况令我困扰。这是我的代码。

Using Java 8 great feature CompletableFuture, I'd like to transform my old async code using exceptions to this new feature. But the checked exception is something bothering me. Here is my code.

CompletableFuture<Void> asyncTaskCompletableFuture = 
                CompletableFuture.supplyAsync(t -> processor.process(taskParam));

进程的签名方法:

public void process(Message msg) throws MyException;

如何处理ComletableFuture中的已检查异常?

How do I deal with that checked exception in ComletableFuture?

推荐答案

我试过这种方式,但我不知道这是否是解决问题的好办法。

I have tried this way, but I don't know whether it's a good way to solve the problem.

@FunctionalInterface
public interface RiskEngineFuncMessageProcessor<Void> extends Supplier<Void> {
    @Override
    default Void get() {
        try {
            return acceptThrows();
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }

    Void acceptThrows() throws Exception;

使用Supplier的FunctionalInterface,我可以包装例外:

With the FunctionalInterface of Supplier, I can wrap the exception:

final MyFuncProcessor<Void> func = () -> {
            processor.process(taskParam);
            return null;
        };

        CompletableFuture<Void> asyncTaskCompletableFuture =
                CompletableFuture.supplyAsync(func)
                        .thenAccept(act -> {
                            finishTask();
                        })
                        .exceptionally(exp -> {
                            log.error("Failed to consume task", exp);
                            failTask( exp.getMessage());
                            return null;
                        });

这篇关于使用CompletableFuture检查异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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