java / expert
Snippet
Customizing Reactive Error Mapping in WebFlux
In Spring WebFlux, customizing global error responses requires extending DefaultErrorAttributes. This allows you to inject business-specific metadata and clean up sensitive stack trace information from the response body for all reactive endpoints.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Componentpublic class GlobalErrorAttributes extends DefaultErrorAttributes {@Overridepublic Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {Map<String, Object> map = super.getErrorAttributes(request, options);Throwable error = getError(request);if (error instanceof BusinessException) {map.put("status", 422);map.put("errorCode", ((BusinessException) error).getErrorCode());}map.remove("path");return map;}}
spring
Breakdown
1
extends DefaultErrorAttributes
Overrides the default mechanism for generating JSON error payloads in WebFlux.
2
getError(request)
Retrieves the actual Throwable that triggered the error response from the current request context.
3
map.put("errorCode", ...)
Enriches the response with a custom error code defined in our internal business logic.