apollo-kotlin icon indicating copy to clipboard operation
apollo-kotlin copied to clipboard

onFailure- ApolloException, No getting server error message

Open khushhalblulabs opened this issue 2 years ago • 3 comments

{"errors":[{"message":"Not Patient Found","locations":[{"line":1,"column":68}],"path":["getCareTeam"],"extensions":{"code":"UNAUTHENTICATED"}}],"data":{"getCareTeam":null}}

This above is my server error that I want to parse in my apollo client response, but onResponse() function didn't called, I am getting Apollo Exception in onFailure() function but not able to get this error from apollo exception

I am getting the following in exception com.apollographql.apollo3.exception.ApolloHttpException: Http request failed with status code401``

By using okHttp Client logger in request, I am able to get this error in logs, but not able to get in my callback function

image

khushhalblulabs avatar Aug 24 '22 07:08 khushhalblulabs

Hi!

It looks like the backend replies with a 401 error, which in Apollo Kotlin means that it will not treat it as a valid GraphQL response, but a lower-level HTTP error. In that case it will throw the exception you are seeing. However you can still get the content of the body in the exception, if you set httpExposeErrorBody to true in your client, like so:

val apolloClient = ApolloClient.Builder()
  //...
  .httpExposeErrorBody(true)
  .build()

After doing this you will be able to get the body like so:

try {
  apolloClient.query(MyQuery()).execute()
} catch (e: ApolloHttpException) {
  val body: BufferedSource? = e.body ?: return
  // Make it a String
  val bodyStr: String = body.readUtf8()
  // Or, parse the JSON as a Map for instance
  val bodyJsonMap: Map<String, Any?> = BufferedSourceJsonReader(body).readAny() as Map<String, Any?>
  // ...
  // Don't forget to close the body when finished
  body.close()
}

BoD avatar Aug 24 '22 09:08 BoD

Hey, Thanks for the above code snipped, It's working fine with Apollo3 client SDK

Do we have any corresponding solution for this following SDK version as well ? com.apollographql.apollo:apollo-api:2.3.1

because .httpExposeErrorBody property not found in this SDK version

khushhalblulabs avatar Aug 24 '22 11:08 khushhalblulabs

With Apollo v2, you don't need to enable anything specifically - you can get the body by implementing onHttpError on your callback, like so:

            @Override
            public void onHttpError(@NotNull ApolloHttpException e) {
                String bodyString = e.rawResponse().body().string();
                // ...
            }

BoD avatar Aug 24 '22 12:08 BoD

@khushhalblulabs anything else we can help with here?

martinbonnin avatar Oct 03 '22 12:10 martinbonnin

Closing this for now, don't hesitate to re-open if needed.

BoD avatar Nov 03 '22 13:11 BoD