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();
Dependencies Let's start with the spring-boot-starter-webflux dependency, which pulls in all other required dependencies: spring-boot and spring-boot-starter for basic Spring Boot application setup. spring-webflux framework. reactor-core that we need for reactive streams and also reactor-netty.
both infrastructure will compete for the same job (for example, serving static resources, the mappings, etc) mixing both runtime models within the same container is not a good idea and is likely to perform badly or just not work at all.
WebExceptionHandler
is rather low level, so you have to directly deal with the request/response exchange.
Note that:
Mono<Void>
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With