如何处理Retrofit 2.0中的错误 [英] How to handle error in Retrofit 2.0

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

问题描述

我想在Retrofit 2.0中处理错误

I want to handle error in Retrofit 2.0

code = 404 body = null ,但 errorBody()包含中的数据ErrorModel 布尔状态字符串信息

这是 errorBody()。内容 [text = \\\
{status:false,info:提供的电子邮件不存在。}]

如何获取这些数据?

感谢帮助我!

这是我的Retrofit请求的代码:

This is my code for Retrofit request:

ResetPasswordApi.Factory.getInstance().resetPassword(loginEditText.getText().toString())
    .enqueue(new Callback<StatusInfoModel>() {
        @Override
        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));
            }
        }

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


推荐答案

如果您想在错误响应时获取数据(您可以像 onResponse()方法中那样执行:

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

生成 YourErrorPojo.class 执行以下步骤:


  1. 转到 Json Schema 2 Pojo

粘贴您的示例 Json ,并选择源类型 Json ,注释 Gson

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

您的示例 Json 是: {status:false,info:提供的电子邮件不存在。}

将此添加到您的 build.gradle 编译'com.google.code.gson:gson:2.7'

我使用 Gson 在这个解决方案,但你可以得到你的 Json 像: response.errorBody()。string()并处理它,无论你想要什么。

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

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

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