Video in progress

How do you catch an error in a CompletableFuture chain: what is the difference between exceptionally, handle and whenComplete?

exceptionally runs only on error and returns a fallback value. handle is always called and can change both the result and the error. whenComplete is also always called, but doesn't change the result; it is for logging and metrics.

📖 Answer

CompletableFuture<Price> price = pricingClient.fetchAsync(sku)
        .orTimeout(2, TimeUnit.SECONDS)
        .whenComplete((p, ex) -> {
            if (ex != null) metrics.increment("pricing.error");
        })
        .exceptionally(ex -> {
            log.warn("narx olinmadi, keshdan beramiz: {}", sku, ex);
            return priceCache.get(sku);
        });

The differences in one line each:

  • exceptionally(fn): Throwable -> T;
  • handle(fn): (T, Throwable) -> U, one place for both cases;
  • whenComplete(action): (T, Throwable) -> void, the result passes through.

A place where people often go wrong: the exception that reaches a callback is often wrapped in a CompletionException. To check the original cause:

Throwable cause = ex instanceof CompletionException ce ? ce.getCause() : ex;
if (cause instanceof TimeoutException) { ... }

One more thing: join() throws CompletionException (unchecked), while get() throws ExecutionException (checked). Inside a lambda, join() is more convenient.

Java 12+ also has exceptionallyCompose, for sending a fallback request asynchronously on error.