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 Project Reactor (Mono, Flux, operators). It covers what changes when the same error contract runs on Spring WebFlux, the reactive web stack, instead of Spring MVC.
What stays the same
Annotated WebFlux controllers (@RestController, @GetMapping) use the same error-handling annotations as MVC:
@ExceptionHandlermethods, local to a controller or global in a@RestControllerAdvice.@ResponseStatuson exception classes.ResponseStatusExceptionthrown at the call site.ProblemDetailas a return type, producing anapplication/problem+jsonbody.- Bean Validation with
@Valid.
Your OrderNotFoundException can be reused unchanged. The differences come from three facts: errors travel as signals inside a pipeline, there is no servlet container, and validation throws a different exception type.
Errors are signals, not stack unwinding
In MVC, a thrown exception unwinds the call stack to the dispatcher. In a reactive pipeline, nothing runs until someone subscribes, and an error is delivered to subscribers as an onError signal. Reactor converts an exception thrown inside an operator such as map into that signal. Spring subscribes to the Mono or Flux your method returns and routes the error signal to the same @ExceptionHandler methods.
Reactor also gives you operators that handle errors inside the pipeline:
| Operator | Purpose |
|---|---|
| `onErrorMap` | Translate one exception type into another, for example a driver exception into a domain exception |
| `onErrorResume` | Replace the error with a fallback `Mono` or `Flux` |
| `doOnError` | Run a side effect such as logging. The error still propagates |
| `switchIfEmpty` | Replace an empty result with `Mono.error(...)` |
A try/catch around the code that builds the pipeline does not catch errors raised later during subscription. Use the operators instead.
The empty Mono gotcha
If a Mono<Order> completes empty, WebFlux returns 200 OK with an empty body. It does not return 404. You must convert the empty case into an error yourself.
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()));
}
}Mono.error(Supplier) builds the exception only when the empty case actually happens. Mono.error(new OrderNotFoundException(id)) would build it, and capture its stack trace, on every request, even successful ones.
The exception handling chain
MVC uses a chain of HandlerExceptionResolver beans. WebFlux has WebExceptionHandler beans instead. Here is what runs, from most specific to least:
@ExceptionHandlermethods in controllers and advice, tried first for annotated controllers.ResponseStatusExceptionHandler, which mapsResponseStatusExceptionand@ResponseStatusexceptions to a status.- Spring Boot's
DefaultErrorWebExceptionHandler, which replaces MVC'sBasicErrorControllerand/errorpage. It renders the default error body directly and does not forward to an/errorpath, because there is no servlet dispatch.
The server.error.* properties from the earlier chapter still control DefaultErrorWebExceptionHandler, because it uses the same ErrorAttributes mechanism. ProblemDetail for framework exceptions has its own WebFlux switch:
# RFC 9457 bodies for exceptions raised by WebFlux itself
spring.webflux.problemdetails.enabled=true
server.error.include-message=never
server.error.include-binding-errors=never
server.error.include-stacktrace=never
server.error.include-exception=falseValidation raises a different exception
With @Valid on a request body, MVC throws MethodArgumentNotValidException. WebFlux throws WebExchangeBindException. It extends ServerWebInputException, which extends ResponseStatusException. A handler written for the MVC type never fires in a WebFlux application.
The global handler below also deals with a trap. An @ExceptionHandler(Exception.class) catch-all matches every ResponseStatusException too, which would turn your 404s and 400s into 500s. This is the same problem you meet in MVC when you do not extend ResponseEntityExceptionHandler. The fix here is a more specific handler that preserves the status.
package com.example.orders;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.server.ResponseStatusException;
@RestControllerAdvice
public class ApiExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);
@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;
}
@ExceptionHandler(ResponseStatusException.class)
public ResponseEntity<ProblemDetail> handleStatus(ResponseStatusException ex) {
return ResponseEntity.status(ex.getStatusCode())
.headers(ex.getHeaders())
.body(ex.getBody());
}
@ExceptionHandler(Exception.class)
public ProblemDetail handleUnexpected(Exception ex) {
log.error("Unhandled exception", ex);
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
problem.setTitle("Internal server error");
return problem;
}
}Spring picks the handler whose declared exception type is closest to the thrown type. WebExchangeBindException therefore reaches handleValidation, and other ResponseStatusException instances reach handleStatus.
Functional endpoints do not use controller advice
If you define routes with RouterFunction and HandlerFunction, there is no controller, so @ExceptionHandler and @RestControllerAdvice do not apply. You have two options:
- Add
onErrorclauses to the route builder, as below. - Register a custom
WebExceptionHandlerorErrorWebExceptionHandlerbean for application-wide handling.
package com.example.orders;
import java.util.Map;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@Configuration
class OrderRoutes {
private final Map<Long, Order> orders = Map.of(1L, new Order(1L, "Book"));
@Bean
RouterFunction<ServerResponse> functionalOrderRoutes() {
return RouterFunctions.route()
.GET("/fn/orders/{id}", request -> {
long id = Long.parseLong(request.pathVariable("id"));
Order order = orders.get(id);
if (order == null) {
return Mono.error(new OrderNotFoundException(id));
}
return ServerResponse.ok().bodyValue(order);
})
.onError(OrderNotFoundException.class, (ex, request) -> {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Order not found");
return ServerResponse.status(HttpStatus.NOT_FOUND)
.contentType(MediaType.APPLICATION_PROBLEM_JSON)
.bodyValue(problem);
})
.build();
}
}Streaming and committed responses
For a Flux that streams data, the status line and headers go out with the first element. If an error occurs on the tenth element, Spring can no longer change the status to 500. The connection is terminated or the stream ends abnormally, and the client sees a truncated response. Validate and check preconditions before the first element is emitted, and treat mid-stream errors as something the client must detect.
Logging in reactive code
- Do not log in
doOnErrorand again in the advice. The error passes through both, so you get two entries for one failure. - Log once, in the place that decides the response. This is the same rule as in MVC.
- MDC values (the thread-local logging context) can be lost, because a request may hop between threads. Use Reactor's context propagation support if you rely on correlation ids in logs.
- Never call blocking code, such as a synchronous log appender that writes to a slow remote service, inside a handler. It stalls event-loop threads.
Testing with WebTestClient
@WebFluxTest plays the role of @WebMvcTest. It loads the controllers and the @RestControllerAdvice, and WebTestClient replaces MockMvc. The project needs spring-boot-starter-webflux and spring-boot-starter-validation. Do not add spring-boot-starter-web as well, because Spring Boot then starts an MVC application and ignores WebFlux.
package com.example.orders;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;
@WebFluxTest(OrderController.class)
class OrderControllerErrorTest {
@Autowired
WebTestClient client;
@Test
void unknownOrderReturnsProblemDetail() {
client.get().uri("/orders/99")
.exchange()
.expectStatus().isNotFound()
.expectBody()
.jsonPath("$.title").isEqualTo("Order not found")
.jsonPath("$.orderId").isEqualTo(99);
}
@Test
void blankItemReturnsFieldErrors() {
client.post().uri("/orders")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue("{\"item\":\"\",\"quantity\":1}")
.exchange()
.expectStatus().isBadRequest()
.expectBody()
.jsonPath("$.errors[0]").isEqualTo("item: must not be blank");
}
}Summary of differences
| Concern | Spring MVC | Spring WebFlux |
|---|---|---|
| Failure mechanism | Thrown exception unwinds the stack | `onError` signal in a pipeline |
| Resolver chain | `HandlerExceptionResolver` | `WebExceptionHandler` |
| Default error rendering | `BasicErrorController` at `/error` | `DefaultErrorWebExceptionHandler`, no forward |
| Validation exception | `MethodArgumentNotValidException` | `WebExchangeBindException` |
| ProblemDetail property | `spring.mvc.problemdetails.enabled` | `spring.webflux.problemdetails.enabled` |
| Empty result | Controller returns `null` or throws | Empty `Mono` gives 200 unless you convert it |
| Functional endpoints | Not applicable | Need `onError` or a custom handler |
| Test tools | `MockMvc`, `@WebMvcTest` | `WebTestClient`, `@WebFluxTest` |
Exercise
A WebFlux controller method returns Mono.justOrEmpty(repository.find(id)), and the id does not exist. What status does the client receive, and how do you make it a 404 with your OrderNotFoundException?
Show answer
The client receives 200 OK with an empty body, because an empty Mono is a normal completion, not an error. Add .switchIfEmpty(Mono.error(() -> new OrderNotFoundException(id))) so the empty case becomes an error signal, which your @ExceptionHandler maps to a 404 ProblemDetail.
Exercise
Your @RestControllerAdvice has @ExceptionHandler(Exception.class) returning a 500 ProblemDetail. After a refactor, requests that fail with ServerWebInputException (for example, a malformed path variable) start returning 500 instead of 400. Why, and what is the fix?
Show answer
ServerWebInputException is a ResponseStatusException, and the catch-all Exception handler is now the closest match Spring finds, so it swallows the exception. Add an @ExceptionHandler(ResponseStatusException.class) method that returns ResponseEntity.status(ex.getStatusCode()).headers(ex.getHeaders()).body(ex.getBody()). It is more specific than Exception, so it wins and keeps the original status.