Spring Webclient : How to get the body on error when the http status code is 200

Viewed 839

I'm using the webClient from Spring to fetch data from a GraphQL webservice. This code is located in a generic method that decode the response body into different types of objects. If the response are of expected type, it is working well.

webClient()
    .post()
    .bodyValue(graphQLQuery)
    .retrieve()
    .bodyToMono(classType);

I now want to handle errors from the webservice. So fare my problem is very similar to this: Spring Webflux : Webclient : Get body on error I see that it's recommended to use onStatus, but my problem is that even though the respons body is an error (see example below), the http status code is a 200. Is there a way to handle errors, like the onStatus, that don't rely on the http status code?

Here is the response body I receive on errors:

{
  "errors": [
    {
      "message": "Cannot query field \"something\" on type \"Query\".",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "extensions": {
        "code": "FIELDS_ON_CORRECT_TYPE",
        "codes": [
          "FIELDS_ON_CORRECT_TYPE"
        ],
        "number": "5.3.1"
      }
    }
  ]
}
1 Answers

You can simply use flatmap and propagate an error signal if errors are found:

return webClient
    .post()
    .bodyValue(graphQLQuery)
    .retrieve()
    .bodyToMono(classType)
    .flatMap(response ->
          response.getErrors() != null && !response.getErrors().isEmpty() ?
              Mono.error(new MyException("Errors found...")) :
              Mono.just(response)
     );
Related