Retrofit 2 - get a JSON error object (multiple POJOs for one request)

I have a simple query 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 the http code is 200

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

Or a Json error, describes the exact error if something went wrong

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

How can I handle the error status in response?

I tried this, but it does not see JSON in the raw text (does not work). And it does not seem to be a good 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 } } 
+5
source share
1 answer

To access the response body, if you have an error code, use errorBody() instead of body() . In addition, there is a string ResponseBody method 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 } 
+3
source

Source: https://habr.com/ru/post/1233798/


All Articles