Checked exception with CompletableFuture [duplicat

2019-02-14 06:32发布

This question already has an answer here:

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

The signature of process method:

public void process(Message msg) throws MyException;

How do I deal with that checked exception in ComletableFuture?

1条回答
beautiful°
2楼-- · 2019-02-14 06:50

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;

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;
                        });
查看更多
登录 后发表回答