y07k2 y07k2 - 4 years ago 252
Android Question

How to handle error in Retrofit 2.0

I want to handle error in Retrofit 2.0

Got e.g.

, but
contains data in
Boolean status
String info

This is
[text=\n{"status":false,"info":"Provided email doesn't exist."}]

How can I get this data?

Thank for helping me!

This is my code for Retrofit request:

.enqueue(new Callback<StatusInfoModel>() {
public void onResponse(Call<StatusInfoModel> call, Response<StatusInfoModel> response) {
if (response.isSuccessful()) {
showToast(getApplicationContext(), getString(R.string.new_password_sent));
} else {
showToast(getApplicationContext(), getString(R.string.email_not_exist));

public void onFailure(Call<StatusInfoModel> call, Throwable t) {
showToast(getApplicationContext(), "Something went wrong...");

Answer Source

If you want to get data when error response comes (typically a response code except 200) you can do it like that in your onResponse() method:

if (response.code() == 404) {
    Gson gson = new GsonBuilder().create();
    YourErrorPojo pojo = new YourErrorPojo();
    try {
         pojo = gson.fromJson(response.errorBody().string(), YourErrorPojo.class);
         Toast.makeText(getApplicationContext(), pojo.getInfo(), Toast.LENGTH_LONG).show();
    } catch (IOException e) { }

When generating YourErrorPojo.class do following steps :

  1. Go to Json Schema 2 Pojo

  2. Paste your example Json, and select source type Json , annotation Gson

  3. Your example Json is : {"status":false,"info":"Provided email doesn't exist."}

  4. Click Preview and it will generate your Pojo class for you.

Add this to your build.gradle : compile 'com.google.code.gson:gson:2.7'

I used Gson in this solution but you can get your Json like : response.errorBody().string() and handle it, do sth whatever you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download