android - Retrofit 2.0 错误处理方法

标签 android android-studio error-handling retrofit2

我想在 Retrofit 2.0 中处理错误

例如code=404body=null,但是 errorBody() 包含 ErrorModel 中的数据(Boolean status 字符串信息)。

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

我怎样才能得到这些数据?

谢谢你帮助我!

这是我的 Retrofit 请求代码:

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...");
        }
    });

最佳答案

如果您想在错误响应到来时获取数据(通常是 200 以外的响应代码),您可以在 onResponse() 方法中这样做:

if (response.code() == 404) {
    Gson gson = new GsonBuilder().create();
    YourErrorPojo pojo = new YourErrorPojo();
    try {
         pojo = gson.fromJson(response.errorBody().string(), YourErrorPojo.class);
         Toast.makeText(context, pojo.getInfo(), Toast.LENGTH_LONG).show();
    } catch (IOException e) { 
      // handle failure at error parse 
  }
}

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

  1. 转到 Json Schema 2 Pojo

  2. 粘贴你的例子Json,并选择源类型Json,注解Gson

  3. 您的示例 Json 是:{"status":false,"info":"Provided email doesn't exist."

  4. 单击预览,它将为您生成Pojo 类。

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

我在此解决方案中使用了 Gson,但您可以使用以下方法获取 Json 字符串:response.errorBody().string()

关于android - Retrofit 2.0 错误处理方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38304316/

相关文章:

android - onNewPicture() 什么时候被调用?

android - Error :Execution failed for task ':app:transformClassesWithJarMergingForDebug' 的解决方法是什么

android - 在 Android Studio 中切换设计和文本的快捷方式

ios - 神秘的 UIActivityIndi​​catorView 错误?

android - 无法在设备上运行应用

android - 是否可以用C++编写核心逻辑来开发浏览器、android和iphone?

android - 更改蓝牙 SPP 连接的波特率

Android:使用ADB获取所有已安装的包

android - 如何合并两个 Android-Studio 项目

php - Eclipse PHP项目在线问题