Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

In Reactor, what are onErrorResume, onErrorReturn, onErrorMap and doOnError used for? Write a pipeline that maps a WebClient 404 to an empty result and any other error to a ServiceUnavailableException.

onErrorReturn replaces an error with a fallback value and onErrorResume switches to a fallback publisher, so both handle the error and complete normally. onErrorMap translates one exception into another and doOnError adds a side effect such as logging while letting the error continue. To map a WebClient 404 to an empty result and anything else to ServiceUnavailableException, we use onErrorResume(WebClientResponseException.NotFound.class, e -> Mono.empty()) followed by onErrorMap for every other error.

Why this question is asked

In imperative Java, we handle failures with try and catch. In Reactor there is no surrounding block to catch in, because the code runs later, possibly on another thread. Errors travel down the pipeline as a signal instead, and we handle them with operators. Interviewers ask about these four operators because they are easy to mix up, and mixing them up causes real bugs: logging that swallows errors, fallbacks that hide outages, or exceptions leaking out of a client. In this answer, we will recap how errors flow in Reactor, see each operator with its result, write the WebClient pipeline the question asks for, and look at the common mistakes.

1A Quick Recap: An Error Is a Terminal Signal

A Reactor publisher, a Mono or a Flux, sends its subscriber three kinds of signals: onNext for each item, onComplete when it has finished, and onError when something failed. The rule from the Reactive Streams specification is that onError and onComplete are terminal. Once an error is signalled, the sequence is over, and no more items follow.

When a lambda inside map throws, Reactor catches the exception and turns it into an onError signal that flows down to the next operator. Every error operator sits in that path and decides what to do with the signal.

Java
Flux.just(1, 2, 0, 4)
.map(x -> 10 / x) // 10, 5, then ArithmeticException at 0
.subscribe(
v -> System.out.println(v),
e -> System.out.println("error: " + e.getMessage()));
// 10
// 5
// error: / by zero (4 is never processed)

Notice that 4 is never processed. The error terminated the sequence, and operators after map do not see further items. Error handling operators can replace what the subscriber sees, but they cannot resume the original sequence where it stopped.

2OnErrorReturn and onErrorResume: Handle the Error

Both operators catch the error and finish the sequence normally. The difference is what they put in its place.

Java
Flux.just(1, 2, 0, 4).map(x -> 10 / x)
.onErrorReturn(-1) // 10, 5, -1, complete
Flux.just(1, 2, 0, 4).map(x -> 10 / x)
.onErrorResume(e -> Flux.just(100, 200)) // 10, 5, 100, 200, complete
Mono.error(new TimeoutException())
.onErrorResume(TimeoutException.class,
e -> cache.get(id)) // value from the cache, complete

onErrorReturn emits one fixed value and completes. onErrorResume is more general: it receives the exception and returns a whole new publisher to continue with, which can be Mono.empty(), a cached value, a call to another service, or Mono.error with a different exception. Both have overloads that take an exception class or a predicate, so they only handle the errors we name and let others pass through. That filtering is important: catching every error with a fallback is the easiest way to hide an outage.

3OnErrorMap and doOnError: Translate or Observe

The other two operators do not handle the error; the sequence still ends with onError.

Java
Mono.error(new SQLException("deadlock"))
.onErrorMap(e -> new OrderStoreException("could not save", e)) // error is now OrderStoreException
Mono.error(new IllegalStateException("bad"))
.doOnError(e -> log.warn("lookup failed", e)) // logs, then passes the same error on
.subscribe(v -> {}, e -> System.out.println(e.getClass().getSimpleName()));
// IllegalStateException
The four error operators
OperatorWhat it doesSequence ends with
onErrorReturn(value)replaces the error with one valueonNext(value), onComplete
onErrorResume(fn)switches to a fallback publisherwhatever the fallback emits
onErrorMap(fn)translates the exceptiononError(new exception)
doOnError(fn)side effect such as loggingonError(same exception)

onErrorMap translates the exception into another one, usually to hide a low-level type behind a domain or API exception, keeping the original as the cause. doOnError adds a side effect, such as logging or incrementing a metric, and changes nothing about the signal. So a pipeline that only has doOnError still fails; it just fails with a log line.

4The WebClient Pipeline: 404 to Empty, Everything Else to 503

Now the task. When retrieve() sees a 4xx or 5xx status, bodyToMono emits a WebClientResponseException, and for a 404 the specific subclass WebClientResponseException.NotFound. We want a missing item to become an empty Mono, and any other failure, such as a 500, a timeout or a connection refused, to become our own ServiceUnavailableException.

Java
public class ServiceUnavailableException extends RuntimeException {
public ServiceUnavailableException(Throwable cause) { super("catalog unavailable", cause); }
}
public Mono<ItemDto> findItem(String id) {
return client.get().uri("/items/{id}", id)
.retrieve()
.bodyToMono(ItemDto.class)
.onErrorResume(WebClientResponseException.NotFound.class, e -> Mono.empty())
.onErrorMap(e -> !(e instanceof ServiceUnavailableException),
ServiceUnavailableException::new);
}
// 200 with body -> ItemDto, complete
// 404 -> empty Mono, complete
// 500 -> error ServiceUnavailableException(cause: InternalServerError)
// connection refused -> error ServiceUnavailableException(cause: WebClientRequestException)

Order matters. onErrorResume comes first and only for NotFound, so a 404 is handled and the sequence completes empty; onErrorMap never sees it. Every other error passes through onErrorResume untouched and reaches onErrorMap, which wraps it. The predicate !(e instanceof ServiceUnavailableException) prevents double wrapping if an upstream operator already threw our exception. The caller can then use switchIfEmpty to return a 404 from its own controller, and a controller advice can turn ServiceUnavailableException into a 503.

5Common Mistakes

The first mistake is using onErrorResume(e -> Mono.empty()) without an exception type. It turns every failure, including bugs and outages, into an empty result, and the endpoint returns 200 with no data while dashboards stay green. Always name the exceptions a fallback is meant for.

The second is logging with doOnError at every layer. The same exception is logged three or four times, which makes incidents noisy. Log once, at the edge or where the error is finally handled. The third is expecting a Flux to continue after an error: a fallback replaces the rest of the sequence, it does not resume it. When items must be processed independently, the error has to be handled per item inside flatMap.

6Follow-up questions

Does onErrorResume run on 4xx responses if we use exchangeToMono instead of retrieve?

No. exchangeToMono gives us the ClientResponse for every status and does not raise WebClientResponseException by itself, so we check response.statusCode() and decide, for example returning Mono.empty() for 404 and response.createError() for others. retrieve() is the simpler choice when status-based exceptions are what we want, and onStatus lets us customise which statuses raise errors.

What is the difference between onErrorResume and switchIfEmpty?

onErrorResume reacts to an error signal, while switchIfEmpty reacts to a sequence that completed without any item. In our pipeline they work together: the 404 becomes an empty Mono through onErrorResume, and the caller can turn that empty Mono into a 404 response or a default with switchIfEmpty.

Should a timeout also become ServiceUnavailableException?

Usually yes. If we add timeout(Duration.ofSeconds(2)) before the error operators, the TimeoutException reaches onErrorMap and is wrapped like any other failure. Putting timeout before the handlers is the important detail; after them, a timeout would escape untranslated.

7Conclusion

In this answer, we saw that an error in Reactor is a terminal signal, so items after the failure are never processed. onErrorReturn and onErrorResume handle the error by replacing it with a value or a fallback publisher, onErrorMap translates it into another exception, and doOnError only observes it. We wrote a WebClient pipeline that turns a 404 into an empty Mono with a typed onErrorResume and wraps every other failure in ServiceUnavailableException with onErrorMap, and we looked at the mistakes of untyped fallbacks and repeated logging.

What to say in the interviewAbout 90 seconds aloud

Open with

In Reactor an error is a terminal signal, so once it happens the sequence is over and later items are not processed. The four operators differ in whether they handle the error. onErrorReturn replaces the error with a single fallback value and completes. onErrorResume is the general version: it gets the exception and returns a fallback publisher, which can be empty, a cached value or another call.

Then, if they want more

Both can be limited to an exception type, which I always do so I do not hide real failures. onErrorMap does not handle the error, it translates it, for example wrapping an SQLException in a domain exception. doOnError is only a side effect, like logging or a metric, and the same error carries on.

For the WebClient case, I call retrieve and bodyToMono, then onErrorResume with WebClientResponseException.NotFound.class returning Mono.empty, so a 404 becomes an empty result. After that, onErrorMap with a predicate that skips ServiceUnavailableException wraps every other error, a 500, a connection failure or a timeout, into ServiceUnavailableException with the original as cause.

The order matters: the 404 is handled first so onErrorMap never sees it. The caller can use switchIfEmpty for the empty case, and a controller advice turns ServiceUnavailableException into a 503. I also log once at the edge rather than with doOnError at every layer.

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 Reactor, what are onErrorResume, onErrorReturn, onErrorMap and doOnError used for?...": https://scrivio-interview-library.netlify.app/spring-boot/webflux/175f8fd4f8/