Getting JSON from RetrofitError object using Retrofit

You can use the getBodyAs method of the RetrofitError object. It converts the response to a Java object similarly to other Retrofit conversions. First define a class that describes your JSON error response:

class RestError {
    public int code;
    public String errorDetails;

Then use the previously mentioned method to get the object that describes the error in more detail.

catch(RetrofitError error) {
    if (error.getResponse() != null) {
        RestError body = (RestError) error.getBodyAs(RestError.class);
        switch (body.code) {
            case 101:
            case 102:

Retrofit 2.0 changed the way error responses are converter. You will need to get the right converter with the responseBodyConverter method and use it to convert the error body of the response. Barring exception handling this would be:

Converter<ResponseBody, RestError> converter 
    = retrofit.responseBodyConverter(RestError.class, new Annotation[0]);
RestError errorResponse = converter.convert(response.errorBody());

Leave a Comment