如何使用 Retrofit 2 获取错误正文响应

NoN*_*me2 5 android retrofit retrofit2

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

{
    "success": false,
    "error": {
        "message": {
            "name": [
                "This input is required."
            ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 6

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

@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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Onu*_* D. -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());
    }
}
Run Code Online (Sandbox Code Playgroud)