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
}
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With