Oleksii Matiash
Oleksii Matiash

Reputation: 141

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?

Upvotes: 14

Views: 2778

Answers (2)

Joshua Pinter
Joshua Pinter

Reputation: 47551

Simple Solution with getBodyAs to get a JSON Object.

JsonObject responseAsJson = (JsonObject) retrofitError.getBodyAs(JsonElement.class);

String  message = responseAsJson.get("Message").getAsString(); //=> "readable reason"
Integer      id = responseAsJson.get("Id").getAsInt();         //=> 0

Confirmed working in Retrofit 1.x. Not sure what changes are required for Retrofit 2.x.

Upvotes: 0

Gowtham Raj
Gowtham Raj

Reputation: 2955

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()));
    }

Upvotes: 1

Related Questions