【问题标题】:How to handle errors with Retrofit?如何处理 Retrofit 的错误?
【发布时间】:2017-05-23 04:40:15
【问题描述】:

我的服务器为所有请求返回一个基本的 JSON 结构,例如:

{  
    "success": false,
    "data": {  
        "errors": {  
            "email": [  
                "This is not an email."
            ],
            "password": [  
                "The password must be at least 6 characters."
            ]
        }
    }
}

其中success 可以是真或假,并且数据可以返回许多东西,从errors 到应用程序可能需要的数据。

如何使用 Retrofit 处理此响应(成功和错误)?

我的 Retrofit API 调用需要更改/添加哪些内容?

Call<BasicResponse> call = apiService.login(emailString, passwordString);
call.enqueue(new Callback<BasicResponse>() {
    @Override
    public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
        //
    }

    @Override
    public void onFailure(Call<BasicResponse> call, Throwable t) {
        //
    }
});

【问题讨论】:

    标签: retrofit retrofit2


    【解决方案1】:

    基本上你会想要使用你的模型。你有几个选择,但最终归结为你的 api 的响应代码以及你如何构建你的模型。

    让我们先把模型弄出来。处理对象是否有错误的一种方法是将其包含在模型的字段中。假设你有错误对象:

    public class Errors {
      // ...
    }
    

    这表示您的 json 中的错误对象:

    "errors": {  
            "email": [  
                "This is not an email."
            ],
            "password": [  
                "The password must be at least 6 characters."
            ]
        }
    

    现在假设你有一个数据对象来表示 json 对象:

    "data": {  
        "errors": {  
            "email": [  
                "This is not an email."
            ],
            "password": [  
                "The password must be at least 6 characters."
            ]
        }
    }
    

    你可以简单地拥有:

    public class Data {
       @SerializedName("success")
       @Expose
       private boolean success;
       @SerializedName("errors")
       @Expose
       private Errors errors;
       // Here you can then add other models, i.e:
       // @SerializedName("user")
       // @Expose
       // private User user;
     }
    

    如您所见,您可以将其余模型添加到Data 对象。当响应成功时,errors 将为空,success 为真。当响应不成功时,您将遇到相反的情况。您可以查看answer 了解更多详细信息以及实现此目的的其他方法。

    现在到您处理错误响应的部分。

    如果您的呼叫成功,您最终将进入onResponse 呼叫。这意味着您必须先检查Data.success 的值,然后才能开始与对象交互。如果false 你知道你可以访问errors 字段而不产生NullPointerException,如果true 你知道你已经正确检索了数据。

    onFailure 仅在套接字超时或序列化和反序列化请求等异常时调用。

    【讨论】:

    • onFailure 回调接受哪些错误代码?现在,如果出现错误,我的服务器会以 400 进行响应,但这是在 onResponse 回调中处理的。
    • 抱歉,我的印象是改造会为每个非 2xx http 状态调用onFailure,但它实际上调用了onResponse。它对所有状态代码执行此操作,因为它们实际上成功地进行了调用。我将编辑我的答案。
    猜你喜欢
    • 2016-11-13
    • 2017-01-01
    • 2016-03-03
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2016-06-29
    • 1970-01-01
    相关资源
    最近更新 更多