Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:{}
}
like image 415
Qiaosen Huang Avatar asked Jun 30 '15 04:06

Qiaosen Huang


1 Answers

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());
    }
like image 98
Amandeep Rohila Avatar answered Sep 30 '22 06:09

Amandeep Rohila