java / expert
Snippet
Global Reactive Error Handling with WebExceptionHandler
In Spring WebFlux, @ControllerAdvice is often insufficient for errors occurring outside the controller context. Extending AbstractErrorWebExceptionHandler allows for low-level, non-blocking control over the global error response pipeline.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Component@Order(-2)public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {public GlobalErrorWebExceptionHandler(ErrorAttributes errorAttributes, WebProperties webProperties, ApplicationContext applicationContext, ServerCodecConfigurer configurer) {super(errorAttributes, webProperties.getResources(), applicationContext);this.setMessageWriters(configurer.getWriters());}@Overrideprotected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {return RouterFunctions.route(RequestPredicates.all(), request -> {Map<String, Object> error = errorAttributes.getErrorAttributes(request, ErrorAttributeOptions.defaults());return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).bodyValue(error);});}}
spring
Breakdown
1
@Order(-2)
Ensures this handler takes precedence over the default Spring Boot error handlers.
2
getRoutingFunction(ErrorAttributes errorAttributes)
Defines the logic to route all errors to a specific functional response handler.