Corrected exception with CompletableFuture

Using the Java 8excellent CompletableFuture function, I would like to convert the old old asynchronous code using exceptions for this new function. But a checked exception is what bothers me. Here is my code.

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

Method Signature process:

public void process(Message msg) throws MyException;

How can I handle this checked exception in ComletableFuture?

+4
source share
1 answer

I tried this way, but I do not know if this is 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 the provider, I can throw an 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;
                        });
+2
source

Source: https://habr.com/ru/post/1653733/


All Articles