1

I use Retrofit 2.0.2 and I can't get error body json and convert it. Here my code:

public RestClient() {
    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    apiInterface = retrofit.create(ApiInterface.class);
}

        @FormUrlEncoded
    @POST("users/login")
    Call<Person> login(@FieldMap Map<String, String> map);

    private void login(Map<String, String> map) {
    Call<Person> call = restClient.getApiInterface().login(map);

    Log.d("Login_call", call.request().toString());

    call.enqueue(new Callback<Person>() {
        @Override
        public void onResponse(Call<Person> call, Response<Person> response) {
            Log.d("Login_call", response.isSuccessful() + " " + response.message());
            if (response.isSuccessful()) {
                Log.d("Login_call", response.body().toString());
                //editor.putString("user", new Gson().toJson(response.body()));
                //editor.apply();
            }
            else {
                Log.d("Login_call", response.errorBody().toString());
            }
        }

        @Override
        public void onFailure(Call<Person> call, Throwable t) {
            Log.d("Login_call_fail", "Fail");
        }
    });
}

and here my Logs:

05-11 17:54:09.961 2606-2606/ D/Login_call: false Bad Request

05-11 17:54:09.961 2606-2606/ D/Login_call: okhttp3.ResponseBody$1@41ef0e18

How to solve this?

zxc123qwe098qqq
  • 165
  • 2
  • 4
  • 13

5 Answers5

7

I found an answer to my question here Maybe it will help someone. .

First you should create model for error

public class ApiError {

@SerializedName("status")
private String status;

@SerializedName("message")
private String message;

public String getStatus() {
    return status;
}

public String getMessage() {
    return message;
}

@Override
public String toString() {
    return "ApiError{" +
            "status='" + status + '\'' +
            ", message='" + message + '\'' +
            '}';
   }
}

Second step is create class which convert json to Error model Here my implementation:

public class ErrorUtils {

public static ApiError parseError(RestClient client, Response<?> response) {

    Converter<ResponseBody, ApiError> converter = client.getRetrofit()
            .responseBodyConverter(ApiError.class, new Annotation[0]);

    ApiError error;

    try {
        error = converter.convert(response.errorBody());
    } catch (IOException e) {
        return new ApiError();
    }

    return error;
    }
}

And you can use like this:

    private void login(Map<String, String> map) {
    Call<Person> call = restClient.getApiInterface().login(map);

    Log.d("Login_call", call.request().toString());

    call.enqueue(new Callback<Person>() {
        @Override
        public void onResponse(Call<Person> call, Response<Person> response) {
            Log.d("Login_call", response.isSuccessful() + " " + response.message());
            if (response.isSuccessful()) {
                Log.d("Login_call", response.body().toString());
                //editor.putString("user", new Gson().toJson(response.body()));
                //editor.apply();
            }
            else {
                Log.d("Login_call", response.code() + "");
                ApiError error = ErrorUtils.parseError(restClient, response);
                Log.d("Login_call_error", error.toString() + "");
            }
        }

        @Override
        public void onFailure(Call<Person> call, Throwable t) {
            Log.d("Login_call_fail", "Fail");
        }
    });
}

Thanks!

Dheeraj Rijhwani
  • 351
  • 5
  • 18
zxc123qwe098qqq
  • 165
  • 2
  • 4
  • 13
1
   String data=response.errorBody().string();
   try {
            JSONObject jObjError = new JSONObject(data);
         Toast.makeText(getContext(),jObjError.getString("message"), 
         Toast.LENGTH_LONG).show();
      } 
  catch (Exception e) {
        Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();

      }

Happy coding..

Bharat Kumar Emani
  • 3,436
  • 3
  • 16
  • 30
0

use

Gson().fromJson(response.errorBody()?.string(),Your class Name)

you can also use both in one

Gson().fromJson(response.body()?.string()?:response.errorBody()?.string(),Your Class Name)
Zoe
  • 27,060
  • 21
  • 118
  • 148
0

the solution is here https://stackoverflow.com/a/70135493/4882029

it work fine for me. If this error response still in json, use GSON to convert it to object like this

new Gson().fromJson( errorResult.toString(), MyObject.class);
hamil.Dev
  • 137
  • 2
  • 9
0

use

in Kotlin

response()?.errorBody()?.string()?:"errorMessage empty"
JellyCan
  • 11
  • 1
  • 2