retrofit: Converting response.errorBody()
Can somebody provide example of converting response.errorBody()
to some Error class or String or JSON ? I’ve tried this kind of converter and this approach, but i always get null
?
In my case server responds with
"Message": "Authorization has been denied for this request."
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Reactions: 1
- Comments: 23 (4 by maintainers)
I found a better way to convert errorbody to JSONObject if you dont have time for creating ResponseError classes. Just do
JSONObject jObjError = new JSONObject (response.errorBody().string())
No silly converter required, no bufferedreader, plain old JSONObject as ususal
I’ve managed to do this with also
Converter
now. I think this is better solution. This is error returned from server:I have this class for modeling this error:
And this is code for getting error message from
response.errorBody()
:Is there a new / better solution for this? The current retrofit2 snapshot does not provide
Retrofit retrofit
in theonResponse
Callback anymore 😦responseConverter is now responseBodyConverter
Update: Working for retrofit2
@meetmkjangid Strangely, if you call
response.errorBody().string()
twice, the second time it returns empty.Eg:
Just call
.string()
on it thenThat’s not strange, that’s how a ResponseBody works. It’s a resource you read.
On Mon, Oct 3, 2016, 6:46 PM RmK notifications@github.com wrote:
I have found this solution, i am not sure if it good solution. It converts
errorBody
to String:Convert
response.errorBody().string()
to an array of your custom model. Use Gson or any other (de)serialization library for the conversion.Share the StackOverflow link, I will provide the sample code.
Thanks @JakeWharton . My understanding was that it could be read any number of times. I guess that’s not possible.