如何处理Retrofit 2.0中的错误

y07*_*7k2 11 error-handling android android-studio retrofit2

我想在Retrofit 2.0中处理错误

得到eg code=404body=null,但errorBody()包含ErrorModel(Boolean statusString info)中的数据.

这是errorBody().content:[text=\n{"status":false,"info":"Provided email doesn't exist."}].

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

谢谢你的帮助!

这是我的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...");
        }
    });
Run Code Online (Sandbox Code Playgroud)

Yas*_*maz 12

如果您想在出现错误响应时获取数据(通常是除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(getApplicationContext(), pojo.getInfo(), Toast.LENGTH_LONG).show();
    } catch (IOException e) { }
}
Run Code Online (Sandbox Code Playgroud)

生成时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()处理它,做任何你想做的事情.


Tim*_*Tim 5

Retrofit doesn't see 404 as a failure, so it will enter the onSuccess.

response.isSuccessful() is true if the response code is in the range of 200-300, so it will enter the else there.

if (response.isSuccessful()) {
    showToast(getApplicationContext(), getString(R.string.new_password_sent));
} else {
    // A 404 will go here

    showToast(getApplicationContext(), getString(R.string.email_not_exist));
}
Run Code Online (Sandbox Code Playgroud)

However since your response was not successful, you do not get the response body with .body(), but with errorBody(), errorBody will filled when the request was a success, but response.isSuccessful() returns false (so in case of a status code that is not 200-300).