Search code examples
androiderror-handlingretrofit2pojo

How to parse an error response with Retrofit2?


I'm able to parse a successful 200 response no problem with a pojo for GoodData. However on a 412, I want to parse the response to get the data it returns so that I can do something with it.

I have a Pojo BadResponseData but getting the response body for it it’s always null. I’ve tried using a converter, but this requires having a retrofit instance to work from which I can’t seem to get. What am I missing? I can't find anything in the Android docs that have helped me understand how this works.

Eg:

    public void onResponse(Call<CheckInData> call, Response<GoodData> response) {
            if (response.isSuccessful()) {
                GoodData goodData = response.body();
                if (goodData!= null) {
                  //do something
                } 
            } else {
                BadResponseData badResponseData = response.body();
        //badResponseData is always null!! Why?       
             }

…

The json returned with a 412:

{
    “dataToUse”: {
        “@name”: “A Name”,
        “@date”: "2017-12-11T18:00:00-05:00"
    },
    "serviceErrors": {
        "code": "0",
        "fields": “required.data.not.found”,
        "message": “name”
    }
}

And my pojo classes:

public class BadResponseData {
    private DataToUse dataToUse;
    public DataToUse getDataToUse() { return this.dataToUse; }
    public void setDataToUse(DataToUse dataToUse) { this.dataToUse = dataToUse; }
    private ServiceErrors serviceErrors;
    public ServiceErrors getServiceErrors() { return this.serviceErrors; }
    public void setServiceErrors(ServiceErrors serviceErrors) { this.serviceErrors = serviceErrors; }

}
public class DataToUse {
    private String name;
    public String getName() { return this.name; }
    public void setName(String name) { this.name = name; }
    private Date date;
    public Date getDate() { return this.date; }
    public void setDate(Date date) { this.date = date; }
}

public class ServiceErrors {
    private String code;
    public String getCode() { return this.code; }
    public void setCode(String code) { this.code = code; }
    private String fields;
    public String getFields() { return this.fields; }
    public void setFields(String fields) { this.fields = fields; }
    private String message;
    public String getMessage() { return this.message; }
    public void setMessage(String message) { this.message = message; }
}

Solution

  • You can use response.errorBody() and parse the json:

    ResponseBody errorBody = response.errorBody();
    if (errorBody != null){
        BadResponseData error = new Gson().fromJson(errorBody.charStream(), BadResponseData.class);
    }