Qiaosen Huang
Qiaosen Huang

Reputation: 1133

Retrofit how to handle two type responses?

I have an API server for an Android application.

I'm trying to use Retrofit for it.

The api server can return normal, say /users

{
    "userId":"123",
    "username":"John Doe"
}

but it might also return an error.

{
    "errorCode":0,
    "errorMessage":"blah"
}

So I'm just wondering, Is there a way to handle the errors globally for every method in Retrofit?

Edit:

I ended up with modifying server outpus.

{
    data:[],
    error:{}
}

Upvotes: 7

Views: 976

Answers (1)

Amandeep Rohila
Amandeep Rohila

Reputation: 3588

make method of api using JsonObject as shown below

 Call<JsonObject> listRes(@Body GsonRegisterUser user);

and now used

Call<JsonObject> call = listenerRegisterUser.listRes(gsonRegisterUser);

Now you will get json response by using following method and you can parse according to your requirement

@Override
    public void onResponse(Response<JsonObject> response) {
            Log.e(TAG,response.body().toString());
    }

Upvotes: 1

Related Questions