0

I'm using Retrofit and Gson to get data from REST service. It's works perfectly, but only when API not returning error. Normally, API return list of objects (as json), but when error occurring, API return a single error object. I'm trying to obtain Call<List<Link>> but when API error occurred I'm getting Gson parse error (Expected BEGIN_OBJECT but was BEGIN_ARRAY).

I've only one solution: retrieving single string and then in enqueue's onResponse() try to parse response, but here is a lot of boilerplate code.

Is there any better solution of this problem? How to handle API's errors?

rubin94
  • 502
  • 1
  • 5
  • 12

1 Answers1

0

You can use next construction:

@Override
public void onResponse(Call<YourModel> call, Response<YourModel> response) {
    if (response.isSuccessful()) {
       // Do awesome stuff
    } else if (response.code == 401) {
       // Handle unauthorized
    } else {
       // Handle other responses
    }
}

Full answer: How to get Retrofit success responce status codes

EDIT

For your case you can use Call<JsonElement> as response type and parse it in Response:

    call.enqueue(new Callback<JsonElement>() {
        @Override
        public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
            if(response.isSuccessful()){
                JsonElement jsonElement = response.body();
                if(jsonElement.isJsonObject()){
                    JsonObject objectWhichYouNeed = jsonElement.getAsJsonObject();
                } 
                // or you can use jsonElement.getAsJsonArray() method
                //use any json deserializer to convert to your class.
            }
            else{
                System.out.println(response.message());
            }
        }
        @Override
        public void onFailure(Call<JsonElement> call, Throwable t) {
            System.out.println("Failed");
        }
    });
Community
  • 1
  • 1
kkost
  • 3,640
  • 5
  • 41
  • 72
  • it's not working, only onFailure() is called. API returning JSON which contains message, it's not http error. – rubin94 Sep 01 '16 at 13:54
  • Thanks, this is solution of my problem. But I have decided to modify my model classes and create custom deserializer. – rubin94 Sep 01 '16 at 21:22