rubin94 rubin94 - 3 months ago 32
JSON Question

Multiple retrofit response and API's error handling

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?

Answer

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