Webclient 200 status code with failure in responseBody

Viewed 633

I am using webClient to make call to services 1 that call services 2 and then services 2 fetches data from database and returns them. Problem: I have onStatus to catch bad responses, so responses with 400 or 500 status codes. Code Example:

     return webClient.post()
                     .uri('/example')
                     .header('someHeader')
                     .body(PojoBody)
                     .retrieve()
                     .onStatus(HttpStatus:isError, handleError)
                     .bodyToMono(ResponsePojo);

In some edge cases, response is coming with 200 status code and response body has failure message and reason for failure. So how can I retrieve that and then throw an exception with that failure message (in response object returned by other services). Since it tries to map and throws error. Currently I am getting 500 internal server error. Any help will be greatly appreciated thanks.

1 Answers

The onStatus method lets you handle specific HTTP status responses. You can use it for successful responses as well:

  .onStatus(HttpStatus::is2xxSuccessful, this::handleSuccess)
  .onStatus(HttpStatus::isError, this::handleError)  
Related