Sub topic 10
Handling errors and mapping them to HTTP responses
This chapter assumes you know how Mono and Flux pipelines are built with map and flatMap. It also assumes you can write a WebFlux annotated controller.
Errors are signals, not thrown exceptions
In a reactive pipeline, an error is a signal that travels downstream. It is the onError signal of the Reactive Streams contract. It ends the sequence, and no further items are emitted.
A try/catch around the line that builds a pipeline does not catch these errors. The pipeline runs later, when something subscribes, and often on another thread. You handle errors with operators inside the pipeline instead.
Two things are easy to confuse:
- An empty Mono completes with no value. It is not an error.
- An error signal carries a
Throwable. If nothing handles it, WebFlux turns it into a 500 response.
Recovering inside the pipeline
Use these operators when the failure has a sensible local answer:
onErrorReturn(value)replaces any error with one fallback value.onErrorResume(type, fn)switches to another publisher for a given exception type.onErrorMap(fn)translates one exception into another and keeps the error.
Mono<Book> safe = repository.findById(id)
.onErrorResume(DataAccessException.class, ex -> Mono.empty());Here a database failure becomes an empty result. Use this only when hiding the failure is acceptable. Otherwise you lose information.
Turning empty results into 404
A missing record is empty, not an error. To produce a 404, convert emptiness into an error with switchIfEmpty:
@GetMapping("/{id}")
public Mono<Book> get(@PathVariable String id) {
return repository.findById(id)
.switchIfEmpty(Mono.error(
new ResponseStatusException(HttpStatus.NOT_FOUND)));
}ResponseStatusException carries an HTTP status. WebFlux uses that status when it writes the response.
Pass Mono.error(...) rather than throwing in the argument. Writing switchIfEmpty(Mono.error(new X())) is fine. For expensive or side-effecting fallbacks, use Mono.defer(() -> ...) so the fallback is built only when needed.
Centralizing the mapping
A domain exception keeps your service code free of HTTP details. Map it to a response in one place:
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
class BookNotFoundException extends RuntimeException {
BookNotFoundException(String id) {
super("Book " + id + " not found");
}
}
@RestControllerAdvice
class ApiExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
ResponseEntity<Map<String, String>> notFound(BookNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(Map.of("error", ex.getMessage()));
}
}The controller then uses switchIfEmpty(Mono.error(new BookNotFoundException(id))). The advice catches the error signal and builds the JSON body. The same handler also applies to errors thrown synchronously from the controller method.
Functional endpoints
Functional endpoints have no controller advice by default. Handle the empty case in the handler itself, as in the earlier BookHandler: switchIfEmpty(ServerResponse.notFound().build()). For other errors, add onErrorResume in the handler and return a ServerResponse with the status you want.
Common mistakes
- Putting
onErrorResumebefore the operator that fails. It only sees errors from upstream, so place it after. - Swallowing errors with
onErrorResume(e -> Mono.empty())for every type. Callers then get a silent 200 or 404 and you get no logs. - Calling
.block()in a handler to usetry/catch. This stalls the event loop. - Forgetting that an error ends the sequence. A Flux that fails midway sends nothing more unless you recover.
Exercise
A repository lookup returns an empty Mono for an unknown id. Your controller returns it directly, and clients get 200 with an empty body. Which operator fixes this so clients get 404, and why is onErrorResume not the right tool?
Show answer
Add switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))). An empty Mono is a completion with no value, not an error signal, so onErrorResume never runs. switchIfEmpty reacts to emptiness and substitutes an error, which WebFlux maps to 404.