Issue
I want to handle the Exception of my api by adding a WebExceptionHandler. I can change the status code, but I am stuck when i want to change the body of the response : ex adding the exception message or a custom object.
Does anyone have exemple ?
How I add my WebExceptionHandler :
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(toHttpHandler(routerFunction))
.prependExceptionHandler((serverWebExchange, exception) -> {
exchange.getResponse().setStatusCode(myStatusGivenTheException);
exchange.getResponse().writeAndFlushWith(??)
return Mono.empty();
}).build();
Solution
WebExceptionHandler
is rather low level, so you have to directly deal with the request/response exchange.
Note that:
- the
Mono<Void>
return type should signal the end of the response handling; this is why it should be connected to thePublisher
writing the response - at this level, you're dealing directly with data buffers (no serialization support available)
Your WebExceptionHandler
could look like this:
(serverWebExchange, exception) -> {
exchange.getResponse().setStatusCode(myStatusGivenTheException);
byte[] bytes = "Some text".getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
return exchange.getResponse().writeWith(Flux.just(buffer));
}
Answered By - Brian Clozel
Answer Checked By - Robin (JavaFixing Admin)