如何使用Retrofit2解析错误响应?

时间:2017-12-12 15:59:16

标签: android error-handling retrofit2 pojo

我能够解析一个成功的200响应,没有问题与PoData的GoodData。但是在412上,我想解析响应以获取它返回的数据,以便我可以用它做一些事情。

我有一个Pojo BadResponseData但是为它获取响应主体它始终为null。我已经尝试过使用转换器,但这需要一个改进的实例来工作,我似乎无法获得。我错过了什么?我在Android文档中找不到任何帮助我了解其工作原理的内容。

例如:

    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?       
             }

…

json以412:

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

我的pojo课程:

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; }
}

1 个答案:

答案 0 :(得分:0)

您可以使用response.errorBody()并解析json:

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