Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit getBodyAs() fails to parse server error

I'm trying to parse server message which is sent when something went wrong. Message is sent in JSON:

{
    "Message" : "readable reason",
    "Id" : 0, // reason code
}

Model class for error:

public class RetrofitError
{
    private String message;
    private int id;
}

Retrofit is created with this code:

RestAdapter.Builder builder = new RestAdapter.Builder();

builder.setLog(new AndroidLog(LOG_TAG));
builder.setLogLevel(LogLevel.FULL);
builder.setEndpoint(Constants.getUrl());
builder.setRequestInterceptor(requestInterceptor);

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
gsonBuilder.setPrettyPrinting();

Gson gson = gsonBuilder.create();

builder.setConverter(new GsonConverter(gson));

RestAdapter restAdapter = builder.build();

And the error retrieving:

RetrofitError error = (RetrofitError)retrofitError.getBodyAs(RetrofitError.class)

It works without exceptions, so it seems that I'm doing something like correct. But it constantly fails to parse both fields in the response. Retrofit is created only once, and it successfully retrieves and parses all server responses with except of an error one.

I'm using latest available Retrofit jar - 1.4.1

What am I doing wrong?

like image 411
Alex Matiash Avatar asked Mar 21 '14 12:03

Alex Matiash


1 Answers

Try doing this if you are still facing this issue. I know this is a very old question but it might help others.

    if (restError != null)
        failure(restError);
    else
    {
        failure(new RestError(error.getMessage()));
    }
like image 109
Gowtham Raj Avatar answered Nov 08 '22 00:11

Gowtham Raj