2

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"
      }
    }
  ]
}
Trond
  • 538
  • 6
  • 12

1 Answers1

0

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)
     );
lkatiforis
  • 5,703
  • 2
  • 16
  • 35
  • Tanks lkatiforis. This is surly better error handling than just giving a NullPointerException later on. But is it possible to read the response body on the line where MyException is created? In my code response does not contains .getErrors(). I think .bodyToMono's return is Mono. – Trond Oct 15 '21 at 10:42
  • The `response` is an instance of `classType` specified at `.bodyToMono(classType)`. This class must contain a "list of errors" field (or inherit another class that contains this list). – lkatiforis Oct 15 '21 at 11:01