Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2 - get error-object JSON (few POJO for same request)

I have simple request like

  /*LOGIN*/
        @FormUrlEncoded
        @POST("v1/user/login") //your login function in your api
        Call<LoginResponce> login(@Field("identity") String identity,
               @Field("password") String password);

Which returns either LoginResponceobject if http code 200

{"token":"itwbwKay7iUIOgT-GqnYeS_IXdjJi","user_id":17}

Or Error Json, describes exact error, if something went wrong

{"status":4,"description":"user provided token expired"}

How can I handle error status in response?

I tried this, but it doesn't see JSON in raw text (doens't work). And doesn't seems to be nice solution.

mCallLoginResponse.enqueue(new Callback<LoginResponce>() {
                @Override
                public void onResponse(Response<LoginResponce> response, Retrofit retrofit) {
                    if (response.isSuccess()) {

                        registerWithToken(response.body().getToken());
                    } else { //some error in responce

                        Gson gson = new GsonBuilder().create();
                        ApiError mApiError = gson.fromJson(response.raw().body().toString(), 
ApiError.class); //Exception here - no JSON in String
                            //todo error handling
                        }
                    }
like image 963
DmitryBorodin Avatar asked Oct 19 '22 00:10

DmitryBorodin


1 Answers

To get access to the response body when you have an error code, use errorBody() instead of body(). Also, there is a string method on ResponseBody that you should use instead of toString.

Gson gson = new GsonBuilder().create();
try {
    ApiError mApiError = gson.fromJson(response.errorBody().string(),ApiError.class); 
} catch (IOException e) {
    // handle failure to read error
}
like image 102
iagreen Avatar answered Oct 21 '22 17:10

iagreen