Retrofit 2.0如何获得反序列化的错误响应.body [英] Retrofit 2.0 how to get deserialised error response.body

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

问题描述

我正在使用 Retrofit 2.0.0-beta1

在测试中,我有一个备用方案并且预计错误HTTP 400

In tests i have an alternate scenario and expect error HTTP 400

我想要 retrofit.Response< MyError>响应
response.body()== null

MyError没有反序列化 - 我只在这里看到它

MyError is not deserialised - i see it only here

response.errorBody().string()

但它没有给我MyError作为对象

but it doesn't give me MyError as object

推荐答案

我目前使用非常简单的实现,不需要使用转换器或特殊类。我使用的代码如下:

I currently use a very easy implementation, which does not require to use converters or special classes. The code I use is the following:

public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
    DialogHelper.dismiss();

    if (response.isSuccessful()) {
        // Do your success stuff...
    } else {
        try {
            JSONObject jObjError = new JSONObject(response.errorBody().string());
            Toast.makeText(getContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
}

这篇关于Retrofit 2.0如何获得反序列化的错误响应.body的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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