如何处理Retrofit 2.0中的错误

时间:2016-07-11 10:10:57

标签: android android-studio error-handling retrofit2

我想在Retrofit 2.0中处理错误

得到了code=404body=null,但errorBody()包含ErrorModelBoolean 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...");
        }
    });

4 个答案:

答案 0 :(得分: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) { }
}

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

  1. 转到Json Schema 2 Pojo

  2. 粘贴示例Json,然后选择来源类型 Json ,注释 Gson

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

  4. 点击预览,它会为您生成Pojo课程。
  5. 将此添加到您的build.gradlecompile 'com.google.code.gson:gson:2.7'

    我在此解决方案中使用了Gson但你可以得到Json之类的:response.errorBody().string()并处理它,做任何你想做的事。

答案 1 :(得分:5)

Retrofit没有将404视为失败,因此它将进入onSuccess。

如果响应代码在200-300范围内,则

response.isSuccessful()为true,因此它将在那里输入else。

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

但是,由于您的回复未成功,因此您没有获得.body()的回复正文,但errorBody()回复,请求成功时将填充errorBody,但response.isSuccessful()会返回false(因此,如果状态代码不是200-300)。

答案 2 :(得分:0)

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

  override fun onResponse(call: Call<LoginData>?, response: Response<LoginData>?) {
            if (response != null) {
                if (response.code() == 200 && response.body() != null) {
                    val loginData = response.body()
                    if (loginData != null) {
                     //Handle success case...
                    }
                } else if (response.code() == 401) {
                    val converter = ApiClient.getClient()?.responseBodyConverter<ErrorResponseData>(
                            ErrorResponseData::class.java, arrayOfNulls<Annotation>(0))
                    var errorResponse: ErrorResponseData? = null
                        errorResponse = converter?.convert(response.errorBody())
                        if (errorResponse != null) {
                            //Handle Error case..
                        }
                }
            }
        }

答案 3 :(得分:0)

我正在使用此库Retrobomb,您不必在该级别进行序列化。 易于使用和自定义。它支持每种错误类型或错误代码的注释。 如果您愿意,可以解开所有错误并自行处理。

@ErrorMapping(code = 401, errorType = Unauthorized.class)
@PATCH("/v1/widgets/{id}")
  Single<Widget> updateWidget(@Path("id") String id, @Body Widget widget);