如何通过 Retrofit 2 获得错误主体响应

问题描述 投票:0回答:4

我正在使用 Retrofit 2,我需要处理 JSON 格式的响应错误。以下是响应正文的示例。

{
    "success": false,
    "error": {
        "message": {
            "name": [
                "This input is required."
            ]
        }
    }
}

message
包含有错误的字段列表,这意味着该值是动态的。因此,可能的解决方案之一是将响应正文解析为 JSON 对象。我尝试使用
response.errorBody().string()

获取错误主体
@Override
public void onResponse(final Call<Category> call, final Response<Category> response) {
    if (response.isSuccessful()) {

    } else {
        // Handle error
        String errorBody = response.errorBody().string();
    }
}

不幸的是,打印

errorBody
我只能得到以下结果
{"success":false,"error":{"message":{"name":[""]}}}
Retrofit 是否限制了 errorBody 对象深度?我应该怎么做才能获得可以解析的完整响应正文?

android retrofit retrofit2
4个回答
7
投票

尝试一下我在改造中使用的这个片段。并获取动态错误消息解决方案

@Override
public void onResponse(final Call<Category> call, final Response<Category> response) {
    if (response.isSuccessful()) {

    } else {
        try {
            String errorBody = response.errorBody().string();

            JSONObject jsonObject = new JSONObject(errorBody.trim());

            jsonObject = jsonObject.getJSONObject("error");

            jsonObject = jsonObject.getJSONObject("message");

            Iterator<String> keys = jsonObject.keys();
            String errors = "";
            while (keys.hasNext()) {
                String key = keys.next();
                JSONArray arr = jsonObject.getJSONArray(key);
                for (int i = 0; i < arr.length(); i++) {
                    errors += key + " : " + arr.getString(i) + "\n";
                }
            }
            Common.errorLog("ERRORXV", errors);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

0
投票

我认为如果您尝试response.body.toString(),您会得到完整的响应。


0
投票

这是 Kotlin 中的一个扩展替代方案,用于序列化

errorBody

fun ResponseBody?.responseBodyToString() = this?.charStream()?.readText().toString()

如何使用此示例:

JSONObject(response.errorBody()?.responseBodyToString() ?: "")

然后,您可以做一些类似的事情,在之前的帖子中建议。


-2
投票

只需使用

response.message()

@Override
public void onResponse(final Call<Category> call, final Response<Category> response) {
    if (response.isSuccessful()) {

    } else {
        // Handle error
        Log.i("Response message: ", response.message());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.