Sub topic 14
Differences in Spring WebFlux
This chapter assumes you have read the earlier chapters on @ExceptionHandler, @RestControllerAdvice and ProblemDetail. It also assumes you know the basics of Mono and Flux from Project Reactor. It covers only what changes when you use Spring WebFlux, the reactive web stack, instead of Spring MVC.
What stays the same
If you write annotated controllers, most of your error design carries over:
@RestControllerAdviceand@ExceptionHandlerwork as before.- Your domain exceptions, such as
OrderNotFoundException, are unchanged. - Handler methods can return
ProblemDetail. ResponseStatusExceptionand@ResponseStatusstill map an exception to a status code.
What changes
| Topic | Spring MVC | Spring WebFlux |
|---|---|---|
| Default error handler | `BasicErrorController` and `/error` | `DefaultErrorWebExceptionHandler` |
| Validation exception | `MethodArgumentNotValidException` | `WebExchangeBindException` |
| Base class for framework exceptions | `ResponseEntityExceptionHandler` (servlet version) | `ResponseEntityExceptionHandler` (reactive version, in a different package) |
| Problem details switch | `spring.mvc.problemdetails.enabled` | `spring.webflux.problemdetails.enabled` |
| Functional endpoints | Not applicable | `@ControllerAdvice` does not apply |
The server.error.* properties still tune the default error response. The reactive ResponseEntityExceptionHandler has different method signatures. They take a ServerWebExchange and return Mono<ResponseEntity<Object>>, so code copied from the MVC version will not compile.
Errors are signals, not thrown exceptions
In a reactive pipeline, a failure travels through the chain as an error signal. A controller method returns a Mono or Flux immediately, and the work happens later. To fail a pipeline, return Mono.error(...) instead of throwing. Spring also converts an exception thrown inside an operator into an error signal.
An empty Mono is not an error. It produces a 200 response with an empty body. To produce a 404, turn the empty case into an error with switchIfEmpty.
package com.example.orders;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
record Order(long id, String item) {}
record CreateOrderRequest(@NotBlank String item, @Positive int quantity) {}
@RestController
@RequestMapping("/orders")
class OrderController {
private final Map<Long, Order> orders = Map.of(1L, new Order(1L, "Book"));
@GetMapping("/{id}")
Mono<Order> get(@PathVariable long id) {
return Mono.justOrEmpty(orders.get(id))
.switchIfEmpty(Mono.error(() -> new OrderNotFoundException(id)));
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Mono<Order> create(@Valid @RequestBody CreateOrderRequest request) {
return Mono.just(new Order(2L, request.item()));
}
}The Mono.error call takes a supplier, so the exception is created only when the empty case actually happens.
A global handler for WebFlux
The advice looks almost the same as the MVC one. The main difference is the validation exception type. In WebFlux, a failed @Valid on a request body raises WebExchangeBindException, which implements BindingResult.
package com.example.orders;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
public ProblemDetail handleOrderNotFound(OrderNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Order not found");
problem.setProperty("orderId", ex.getOrderId());
return problem;
}
@ExceptionHandler(WebExchangeBindException.class)
public ProblemDetail handleValidation(WebExchangeBindException ex) {
List<String> errors = ex.getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.toList();
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
problem.setTitle("Invalid request");
problem.setProperty("errors", errors);
return problem;
}
}Enable problem details for the framework's own exceptions with this property:
spring.webflux.problemdetails.enabled=trueFunctional endpoints and local recovery
Router functions do not go through @ControllerAdvice. You have two options:
- Recover inside the pipeline with
onErrorResumeoronErrorReturn, which suits an error that only one operation can produce. - Register a bean that implements
WebExceptionHandler, which suits a rule that applies to the whole application.
Exercise
A WebFlux controller method returns Mono.justOrEmpty(repository.find(id)), and a request for an unknown id gets a 200 with an empty body. How do you make it return a 404 handled by your @RestControllerAdvice?
Show answer
Add .switchIfEmpty(Mono.error(() -> new OrderNotFoundException(id))) to the chain. An empty Mono is a normal completion, so you must convert it into an error signal. The advice's @ExceptionHandler(OrderNotFoundException.class) method then builds the 404 ProblemDetail.