NitishDeshpande
NitishDeshpande

Reputation: 495

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

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?

Upvotes: 1

Views: 2302

Answers (2)

Ryuzaki L
Ryuzaki L

Reputation: 40048

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

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

Upvotes: 0

NitishDeshpande
NitishDeshpande

Reputation: 495

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

Upvotes: 3

Related Questions