如何处理 Retrofit 的错误? [英] How to handle errors with Retrofit?

查看:34
本文介绍了如何处理 Retrofit 的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My server returns a basic JSON structure for all request like:

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

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

Where success can be true or false, and data can return a number of things, from errors to data the app might need.

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

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

What would need to be changed/added to my Retrofit API call?

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) {
        //
    }
});

推荐答案

基本上,您将希望使用您的模型.您在这里有几个选择,但最终归结为 api 的响应代码以及您如何构建模型.

Essentially you'll want to work with your models. You have a couple of options here, but in the end it comes down to the response code of your api and how you structure your models.

让我们先把模型移开.处理有错误或没有错误的对象的一种方法是将此作为模型的字段.假设您有错误对象:

Let's get the models out of the way first. One way you can deal with the object having an error or not is by including this as a field of your models. Say you have the error object:

public class Errors {
  // ...
}

这代表你的 json 中的错误对象:

This represents the errors object in your json:

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

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

Now say you have a data object to represent the json object:

"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 了解更多详情和其他实现方式.

As you can see, you can then add the rest of the models to the Data object. When the response is successful, errors will be null and success true. When the response is unsuccessful you'll have the opposite scenario. You can check this answer for more details and other ways to achieve this.

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

Now to the part where you handle the error response.

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

If your call succeeds you'll end up in the onResponse call. This means that you'll have to check the value of Data.success before you can start interacting with your objects. If false you know you can access the errors field without producing a NullPointerException and if true you know you have the data correctly retrieved.

onFailure 仅在示例套接字超时或序列化和反序列化请求中出现异常时调用.

onFailure is only called when there's an exception in example socket timeout or serialising and deserialising the request.

这篇关于如何处理 Retrofit 的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆