WebExceptionHandler : How to write a body with Spring Webflux

后端 未结 4 1399
情书的邮戳
情书的邮戳 2021-02-19 21:23

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

4条回答
  •  离开以前
    2021-02-19 22:15

    WebExceptionHandler is rather low level, so you have to directly deal with the request/response exchange.

    Note that:

    • the Mono 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));
    }
    

提交回复
热议问题