Java Spring Async Exception Handling for methods with non void return value

1.9k views Asked by At

I have an async function which does a particular task, sample code below,

    @Async
    public CompletableFuture<Boolean> foo(String value) throws Exception {
        // do task
        LOGGER.info("Processing completed");
        return CompletableFuture.completedFuture(true);
    }

Whenever any runtime exception occurs the caller function is not informed and the application runs without any errors/exceptions. This is dangerous because we will be under the false assumption that the processing is successful.

How to avoid this and make the method report error whenever any exception occurs?

2

There are 2 answers

0
NitishDeshpande On

To overcome this you need to add an exception try/catch block and set the exception in the completable future instance

    @Async
    public CompletableFuture<Boolean> foo(String value) {
        CompletableFuture completableFuture = new CompletableFuture();
        try{
            // do task
            LOGGER.info("Processing completed");
            completableFuture.complete(true);
        } catch(Exception e) {
            completableFuture.completeExceptionally(e);
        }
        return completableFuture;
    }

On the caller side,

        CompletableFuture<Boolean> foo = service.foo(value);
        foo.whenComplete((res, ex) -> {
            if (ex == null) {
                // success flow ...
            } else {
                // handle exception ...
                ex.printStackTrace();
                LOGGER.error("ERROR ----> " + ex.getMessage());
            }
        });
0
Ryuzaki L On

You can handle exceptions on the caller side using exceptionally method from CompletableFuture

CompletableFuture<Boolean> foo = service.foo(value)
                                        .exceptionally(ex-> /* some action */ false);