0

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?

NitishDeshpande
  • 435
  • 2
  • 6
  • 19

2 Answers2

1

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());
            }
        });
NitishDeshpande
  • 435
  • 2
  • 6
  • 19
0

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

CompletableFuture<Boolean> foo = service.foo(value)
                                        .exceptionally(ex-> /* some action */ false);
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98