I'm trying to implement custom logging for ResponseStatusExceptions (404 errors and similar).
Web Flux already has a default handler(WebFluxResponseStatusExceptionHandler) for such exceptions, so I thought to implement my own similar handler and log what I need there. I need to log the method, URI, HTTP headers and request body. The body is the only problem, others could be easily retrieved from ServerHttpRequest.
My bean CustomResponseStatusExceptionHandler:
@Slf4j
@Component
@Order(-1) // @Order(-1) needed to process exception before default handler
public class CustomResponseStatusExceptionHandler extends WebFluxResponseStatusExceptionHandler {
public CustomResponseStatusExceptionHandler() {
super();
log.info("Registered bean CustomResponseStatusExceptionHandler");
}
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
if (ex instanceof ResponseStatusException) {
ServerHttpRequest request = exchange.getRequest();
String body = getBodyFromRequest(request.getBody());
log.error("Request body: {}", body);
}
return Mono.error(ex);
}
private String getBodyFromRequest(ServerHttpRequest request) {
return ???;
}
}
Is this even a valid approach to intercept and log 404 errors (and similar)? If yes, then how can I retrieve the request body?