Sub topic 10
Handling errors and mapping them to HTTP responses
This chapter assumes you can write Mono and Flux pipelines with map and flatMap, and that you have built an annotated WebFlux controller. You should also know the basics of Spring Boot exception handling with @ExceptionHandler. The chapter covers how errors travel through a reactive pipeline, how to recover from them, and how to turn them into HTTP responses.
Errors are signals, not thrown exceptions
In a blocking method, an exception unwinds the call stack until a catch block handles it. A reactive pipeline does not work that way. The code that builds the pipeline runs on one call stack, and the code that processes elements runs later, often on another thread. A try/catch around the assembly code cannot see failures that happen at subscription time.
Instead, an error is one of the three signals a publisher can send to its subscriber: onNext, onComplete and onError. onError is terminal. After it, the publisher sends nothing more, and the rest of the upstream sequence is cancelled.
Mono<String> broken = Mono.fromSupplier(() -> {
throw new IllegalStateException("boom");
});
try {
broken.map(String::toUpperCase); // no exception here
} catch (IllegalStateException e) {
// never reached: nothing has run yet
}Nothing runs in this example because nobody subscribed. Even with a subscriber, the exception goes to the onError callback and not to a surrounding catch.
The following diagram shows how an error moves through a pipeline.
Two consequences follow.
- Operators between the failure and the handler are skipped. A
mapplaced after the failing step never sees the error. - If you throw inside a lambda passed to
map,flatMap, orfilter, Reactor catches it and converts it into anonErrorsignal. You do not have to wrap lambdas intry/catchto keep the pipeline alive.
Creating errors
Use Mono.error and Flux.error to produce an error signal on purpose. You often combine them with switchIfEmpty, which runs when a Mono completes without a value.
@GetMapping("/{id}")
public Mono<Book> get(@PathVariable String id) {
return repository.findById(id)
.switchIfEmpty(Mono.error(
new ResponseStatusException(HttpStatus.NOT_FOUND)));
}An empty Mono is not an error. findById completes with no value when the book does not exist. If you return it directly from a controller, WebFlux sends a 200 response with an empty body. Converting emptiness to an error is how you get a 404.
Note that Mono.error(new X()) creates the exception eagerly, even when the Mono is never used. For exceptions that capture a stack trace, prefer the supplier form Mono.error(() -> new X()) so the object is created only when needed.
Recovering inside the pipeline
Reactor offers operators that play the role of catch. Each one replaces the failed sequence with something else.
| Operator | What it does | Typical use |
|---|---|---|
| `onErrorReturn(value)` | Emits a fixed fallback value, then completes | Default values |
| `onErrorResume(fn)` | Switches to another publisher chosen from the error | Fallback lookup, empty result |
| `onErrorMap(fn)` | Translates the error into a different exception | Wrapping low-level exceptions in domain exceptions |
| `doOnError(fn)` | Runs a side effect, such as logging, and passes the error on | Logging |
| `onErrorComplete()` | Swallows the error and completes | Optional, best-effort work |
Each of the first three accepts a type or predicate, so you can handle only the errors you expect.
Mono<Book> safe = repository.findById(id)
.onErrorResume(DataAccessException.class, ex -> Mono.empty());Here a DataAccessException becomes an empty Mono. Any other exception type still travels downstream. Catching everything with onErrorResume(ex -> ...) is tempting, but it hides programming mistakes such as a NullPointerException, so match on specific types.
Wrapping low-level exceptions
onErrorMap keeps persistence details out of your web layer.
public Mono<Book> findBook(String id) {
return repository.findById(id)
.switchIfEmpty(Mono.error(() -> new BookNotFoundException(id)))
.onErrorMap(DataAccessException.class,
ex -> new StorageUnavailableException("Book store failed", ex));
}The service now throws two exception types that mean something to the application. The web layer can map each to a status code.
Logging without swallowing
doOnError observes the error and lets it continue. Use it for logs and metrics.
repository.findById(id)
.doOnError(ex -> log.warn("Lookup failed for {}", id, ex))
.onErrorResume(ex -> Mono.empty());Order matters here. If doOnError came after onErrorResume, it would never fire, because the error has already been replaced.
Mapping errors to HTTP responses
When an error reaches the end of a controller's Mono or Flux, WebFlux turns it into an HTTP response. You have three levels of control.
Level 1: ResponseStatusException
ResponseStatusException carries an HTTP status and an optional reason. WebFlux uses the status directly. This is the quickest option, as in the get method above. The drawback is that your web concepts leak into whatever code creates the exception.
Level 2: @ResponseStatus on a domain exception
You can annotate your own exception class with a fixed status.
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(String id) {
super("No book with id " + id);
}
}This keeps the status next to the exception, but it only supports a constant status and no custom body.
Level 3: @ExceptionHandler and @RestControllerAdvice
For a consistent error format across all controllers, use a controller advice. Handler methods may return plain objects, ResponseEntity, or reactive types.
@RestControllerAdvice
public class ApiExceptionHandler {
public record ApiError(String code, String message) {}
@ExceptionHandler(BookNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ApiError handleNotFound(BookNotFoundException ex) {
return new ApiError("book_not_found", ex.getMessage());
}
@ExceptionHandler(StorageUnavailableException.class)
public ResponseEntity<ApiError> handleStorage(StorageUnavailableException ex) {
return ResponseEntity
.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(new ApiError("storage_unavailable", "Try again later"));
}
}Notice that the handler for the storage failure does not expose ex.getMessage(). Internal messages can leak table names or hostnames, so return a stable, safe message and log the details instead.
The exception handler applies to errors from annotated controllers. It works whether the exception was thrown synchronously in the method or arrived as an onError signal in the returned Mono.
Functional endpoints
Functional endpoints have no controller advice. Handle the error in the handler itself, or register a global WebExceptionHandler bean. Within a handler, onErrorResume can build the response directly.
Mono<ServerResponse> get(ServerRequest request) {
return repository.findById(request.pathVariable("id"))
.flatMap(book -> ServerResponse.ok().bodyValue(book))
.switchIfEmpty(ServerResponse.notFound().build())
.onErrorResume(DataAccessException.class,
ex -> ServerResponse.status(HttpStatus.SERVICE_UNAVAILABLE).build());
}Here switchIfEmpty handles the missing book and onErrorResume handles a failing store, so the two cases map to different statuses.
Errors inside streams
An error ends a Flux. If the fifth element of a ten-element Flux fails, the subscriber receives four elements and then onError. The other five are never produced.
This matters for streaming responses. By the time the error occurs, the server may already have sent a 200 status line and some of the body. You cannot change the status afterward. The connection is closed or the stream ends with an error, and the client sees a truncated response.
To keep a stream alive when individual items may fail, handle the error per element, inside flatMap.
Flux<Result> results = ids.flatMap(id ->
client.fetch(id)
.onErrorResume(ex -> Mono.just(Result.failed(id))));The inner onErrorResume recovers a single item. The outer Flux continues. Without it, the first failing lookup would terminate the whole sequence.
Common mistakes
- Using try/catch around pipeline assembly. It catches only exceptions thrown while building the pipeline, not failures during processing.
- Returning null from a mapper.
maprejects null results with aNullPointerException, which becomes anonErrorsignal. UseflatMapwithMono.empty()orMono.justOrEmptyfor optional values. - Calling
block()in a handler to "catch" errors. On an event-loop thread, Reactor throws an exception because blocking is not allowed there, and the approach defeats the purpose of WebFlux. - Forgetting that errors are terminal. After
onErrorReturn, the original sequence is gone. A Flux that fails on item 5 and usesonErrorReturnemits one fallback value, and not the remaining items. - Placing handlers in the wrong order. An operator only sees errors from upstream, so a handler placed before the failing operator does nothing for it.
- Leaking internal messages. Map exceptions to safe messages in your advice.
Seeing the signals while debugging
The log() operator prints every signal that passes through it, which shows where a pipeline fails.
repository.findById(id)
.log("lookup")
.map(Book::title)
.subscribe(System.out::println,
ex -> System.err.println("Failed: " + ex));The two-argument subscribe shows the explicit error callback. In a WebFlux application the framework subscribes for you, so you rarely write this, but it is useful in tests and scripts.
Exercise
A controller method returns repository.findById(id) and the book does not exist. The client receives 200 with an empty body. Which operator should you add, and what should it contain, to return 404 instead?
Show answer
Add switchIfEmpty(Mono.error(() -> new ResponseStatusException(HttpStatus.NOT_FOUND))) after findById. An empty Mono is a normal completion, not an error, so you must convert it explicitly. A domain exception such as BookNotFoundException handled by a @RestControllerAdvice would work equally well.
Exercise
A Flux of ten items fails on the fifth. You add .onErrorReturn(-1) to the end of the pipeline. What does the subscriber receive?
Show answer
The first four items, then -1, then a completion signal. The error is terminal for the original sequence, so items six to ten are never emitted. To process the remaining items, handle the error per element inside flatMap.