WebExceptionHandler : How to write a body with Spring Webflux

后端 未结 4 1390
情书的邮戳
情书的邮戳 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:04

    Given the answer, to serialize object I use this way :

     Mono db = commonsException.getErrorsResponse().map(errorsResponse -> {
    
         ObjectMapper objectMapper = new ObjectMapper();
         try {
             return objectMapper.writeValueAsBytes(errorsResponse);
         } catch (JsonProcessingException e) {
              return e.getMessage().getBytes();
         }
    }).map(s -> exchange.getResponse().bufferFactory().wrap(s));
    
    exchange.getResponse().getHeaders().add("Content-Type", "application/json");
    exchange.getResponse().setStatusCode(commonsException.getHttpStatus());
    return exchange.getResponse().writeWith(db);
    

提交回复
热议问题