Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

In cf.thenApply(this::parse).exceptionally(ex -> fallback()).thenApply(this::enrich), failures inside enrich are not handled and logs show the exception type CompletionException instead of the real cause. Explain both problems.

There are two separate problems. First, exceptionally only handles failures from the stages before it, and enrich comes after it, so a failure in enrich passes straight through to the end of the chain. Second, when a dependent stage throws, CompletableFuture wraps the exception in a CompletionException, so a handler or log that prints the exception directly shows the wrapper; the real exception is ex.getCause(). We fix the first by putting the recovery after the stages it should cover, and the second by unwrapping before checking types or logging, while taking care to log each failure only once.

Background to this question

This question combines two of the most common surprises in CompletableFuture error handling, and they often appear together in the same chain. Both come from how failures travel through stages, so understanding that one mechanism explains both. In this answer, we will recap how failures move down a chain, reproduce the unhandled failure in enrich, fix the placement of the handler, see where the CompletionException comes from and unwrap it, and finally look at how to avoid logging the same failure many times.

1A Quick Recap: Failures Move Down the Chain

Each method in a chain returns a new future that depends on the previous one. When a stage fails, the next value stage, such as thenApply, is skipped and completes exceptionally with the same failure, and so on down the chain. An error handler like exceptionally is also just a stage. It looks at the result of the stage directly before it: if that failed, it recovers; if it succeeded, it passes the value on.

So a handler has no power over anything added after it. It cannot see the future, only the past.

2Reproducing the Unhandled Failure in enrich

Here is the chain from the question with a parse step that works and an enrich step that fails.

Java
CompletableFuture<Order> result = cf // cf completes with a raw response
.thenApply(this::parse) // ok: Order{id=7}
.exceptionally(ex -> fallback()) // nothing to recover: passes Order{id=7}
.thenApply(this::enrich); // throws IllegalStateException("no customer 7")
result.join();
// throws CompletionException: java.lang.IllegalStateException: no customer 7
// the fallback was never used
Step throughWhich failures the handler can see
  1. thenApply(parse)a failure here is caught by exceptionally
  2. exceptionally(ex -> fallback())sees only the result of parse
  3. thenApply(enrich)a failure here passes the handler by
  4. End of chainjoin() throws CompletionException

4 steps in order. Play them, or step through them one at a time.

Notice that exceptionally sat between parse and enrich. When parse succeeded, exceptionally passed the order along unchanged. Then enrich failed, and there was no handler after it, so the failure reached the end of the chain and join() threw.

3Fix 1: Put the Recovery After the Stages It Should Cover

If the fallback should apply to failures in either step, the handler must come last. If parse and enrich need different reactions, we can keep a handler after each, as long as the last stage that can fail has one after it.

Java
// One fallback for the whole chain
CompletableFuture<Order> result = cf
.thenApply(this::parse)
.thenApply(this::enrich)
.exceptionally(ex -> fallback()); // covers parse and enrich
result.join(); // fallback order
// Different reactions per step
CompletableFuture<Order> result2 = cf
.thenApply(this::parse)
.exceptionally(ex -> fallback()) // a broken response gives the fallback order
.thenApply(this::enrich)
.exceptionally(ex -> notEnriched(ex)); // enrichment failure handled too

So the position of a handler is part of its meaning. A quick review rule is to read the chain from the bottom: the last stage should be a handler, or the future should be returned to a caller who will handle it.

4Where the CompletionException Comes From

The second problem is the type in the logs. When the function inside a dependent stage throws, CompletableFuture catches the exception and completes that stage with a CompletionException whose cause is the original exception. Every later stage receives that same wrapper. It does this so that a single unchecked type can carry any failure, including checked exceptions, from stage to stage.

Java
cf.thenApply(this::parse)
.thenApply(this::enrich)
.exceptionally(ex -> {
log.error("order failed: {}", ex.getClass().getSimpleName()); // CompletionException
log.error("cause: {}", ex.getCause().getClass().getSimpleName()); // IllegalStateException
if (ex instanceof IllegalStateException) { /* never true */ }
return fallback();
});

Notice that an instanceof check on ex itself never matches the real type. This is why alerts and logs show CompletionException with no useful root cause: the code looked at the wrapper.

5Fix 2: Unwrap Before Checking Types or Logging

We unwrap once, in a small helper, and use the result everywhere. The helper peels off CompletionException and ExecutionException, the wrapper get() uses, until it reaches the real cause.

Java
static Throwable unwrap(Throwable ex) {
while ((ex instanceof CompletionException || ex instanceof ExecutionException) && ex.getCause() != null) {
ex = ex.getCause();
}
return ex;
}
.exceptionally(ex -> {
Throwable cause = unwrap(ex); // IllegalStateException: no customer 7
if (cause instanceof IllegalStateException) return notEnriched(cause);
throw new CompletionException(cause); // not ours to handle: pass it on
});

Notice that the handler rethrows what it cannot handle, wrapped again, so the failure keeps travelling. Logging the unwrapped cause, with its stack trace, shows where the failure really happened.

6Log Each Failure Once

Once people learn that failures travel, they sometimes add whenComplete logging after every stage. Then one failure in enrich produces three or four identical stack traces, because each logging stage sees the same failure as it passes. That makes logs noisy and alert counts wrong.

The better rule is to log a failure once, at the place that decides what to do with it: the final handler, or the boundary that returns an error to the user. Intermediate stages either recover or let the failure pass without logging. If a stage needs to add context, such as the order id, it can wrap the cause in a more specific exception and rethrow, and the single log at the end will show both.

7Follow-up questions

Does exceptionally always receive a CompletionException?

Not always. If the handler is attached directly to a future that was completed with completeExceptionally(someException), it receives that exception as it is. Failures that come from a dependent stage, or from supplyAsync, arrive wrapped. Since we cannot easily tell which, unwrapping every time is the safe habit.

Why does CompletableFuture wrap exceptions at all?

Because a stage's function, such as a Function passed to thenApply, cannot throw checked exceptions, and the result needs one type that can carry any failure through the chain and out of join(), which is unchecked. CompletionException is that carrier.

Would handle instead of exceptionally change anything here?

Not the placement problem: handle also only sees the stage before it. It would let us transform the success value at the same point, but it still needs to be after enrich to cover enrich.

8Conclusion

In this answer, we saw that an exceptionally handler only covers the stages before it, so a failure in a later stage like enrich passes it by; the fix is to place recovery after the stages it should cover or add another handler at the end. We also saw that failures in dependent stages are wrapped in CompletionException, so we unwrap to the real cause before checking types or logging, and that we log each failure once, at the boundary that decides what to do with it.

What to say in the interviewAbout 80 seconds aloud

Open with

These are two different problems. The first is placement. exceptionally is just another stage, and it only sees the result of the stages before it. Here it sits between parse and enrich, so when parse succeeds it passes the value on, then enrich throws and there is no handler after it, so the failure goes to the end of the chain.

Then, if they want more

The fix is to put the recovery after the stages it should cover, so move exceptionally to the end, or keep a per-step handler and add another one after enrich. The second problem is the wrapper type.

When a function in a dependent stage throws, CompletableFuture completes the stage with a CompletionException whose cause is the real exception, and every later stage gets that wrapper. So if the handler or the logger looks at ex directly, it sees CompletionException, and instanceof checks against the real type never match.

I would add a small unwrap helper that peels off CompletionException and ExecutionException, then classify and log the cause, and rethrow what the handler cannot deal with. And I would make sure we log the failure only once, at the final handler or the boundary, not with whenComplete at every stage, or one failure shows up as several stack traces.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In cf.thenApply(this::parse).exceptionally(ex -> fallback()).thenApply(this::enrich)...": https://scrivio-interview-library.netlify.app/java/completable-future/0cc05fa420/