Closed ericdsw closed 7 years ago
Retrofit only parses a successful (2xx) response with supplied converter. So when you get an error response from server you need to manually call:
moshi.adapter(Document.class).fromJson(response.errorBody().source())
to deserialize that into a Document
object.
Here's a detailed introduction to error handling in Retrofit: https://futurestud.io/tutorials/retrofit-2-simple-error-handling
I'm currently using this library alongside with Retrofit, and I'm stuck on how to properly read my api's error list from the provided
Document
instance.From what I understand, the
Document
class has the methoderrors()
which should return a list ofmoe.banana.jsonapi2.Error
instances, so I declared myMyAPI
interface like this so i was able to access theDocument
on my callback directly:I already registered the proper
Converter.Factory
instance to the Retrofit client and a success response correctly generates the expectedDocument<Foo>
responseBody.While a success response works, when my api returns an error object and a 4xx status code I no longer can access the parsed
Document
instance.Take this example for instance: say I make a request to the
myApi/foo
endpoint and it generates the following output with a 401 Unauthorized status code:And I have this on my Retrofit instance callback:
The call to
List<Error> errors = response.body().errors()
generates aNullPointerException
because an unsuccessful request'sbody()
method returns null and theerrorBody()
method is the one that contains the actual response data (however,errorBody()
gives an instance ofResponseBody
instead of a parsed instance).My question is: How should I properly parse this kind of error, since an error response will no longer try to parse it to a
Document
instance? Should I make a customJsonAdapter
for an error response? If so, How should I implement it?Any help would be appreciated.