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
WebExceptionHandler
is rather low level, so you have to directly deal with the request/response exchange.
Note that:
Mono
return type should signal the end of the response handling; this is why it should be connected to the Publisher
writing the responseYour 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));
}