Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebExceptionHandler : How to write a body with Spring Webflux

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();
like image 200
adrien le roy Avatar asked Jul 20 '17 09:07

adrien le roy


People also ask

How do you create a spring in WebFlux project?

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.

Can I use Spring MVC and WebFlux together?

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.


1 Answers

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 the Publisher 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));
}
like image 96
Brian Clozel Avatar answered Sep 21 '22 12:09

Brian Clozel