【问题标题】:errorBody() returns null in Retrofit2 despite a rawResponse尽管有 rawResponse,errorBody() 在 Retrofit2 中返回 null
【发布时间】:2018-04-13 00:12:58
【问题描述】:

也许我不懂 apis 或 Retrofit2,但是当我收到 500 Internal Server Error 时,我想适当地通知用户。

当我在收到此错误后记录传入的响应时,当我像这样记录时得到null

    Gson g = new Gson();
    Log.d(TAG, g.toJson(response.errorBody()));

但是,当我记录我的回复时,我会在 rawResponse 中看到 codemessage 等,如下所示:

(为简洁起见,部分 JSON 已被删除)

{  
   "rawResponse":{  
    "body":{  
      "contentLength":0,
         "contentType":{  
            "mediaType":"text/html",
            "subtype":"html",
            "type":"text"
          }
      },
      "code":500,
      "headers":{  
         "namesAndValues":[  ]
      },
      "message":"Internal Server Error",
      "networkResponse":{  
         "code":500,
         "headers":{  },
         "message":"Internal Server Error",
         "protocol":"HTTP_1_1",
         "receivedResponseAtMillis":1509415428600,
         "request":{  },
         "sentRequestAtMillis":1509415428428
      },
      "protocol":"HTTP_1_1",
      "receivedResponseAtMillis":1509415428600,
      "request":{  },
      "sentRequestAtMillis":1509415428428
   }
}

所以我不明白的是,response.errorBody 是从哪里得出的?

【问题讨论】:

    标签: android error-handling response retrofit2


    【解决方案1】:

    对于不成功的响应,errorBody 只是正文本身。

    这可以通过查看 Retrofit 源代码来验证 - Response.java

      /** Create an error response from {@code rawResponse} with {@code body} as the error body. */
      public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) {
        checkNotNull(body, "body == null");
        checkNotNull(rawResponse, "rawResponse == null");
        if (rawResponse.isSuccessful()) {
          throw new IllegalArgumentException("rawResponse should not be successful response");
        }
        return new Response<>(rawResponse, null, body);
      }
    
      private final okhttp3.Response rawResponse;
      private final @Nullable T body;
      private final @Nullable ResponseBody errorBody;
    
      private Response(okhttp3.Response rawResponse, @Nullable T body,
          @Nullable ResponseBody errorBody) {
        this.rawResponse = rawResponse;
        this.body = body;
        this.errorBody = errorBody;
      }
    

    所以在上述情况下,代码为 500,这是不成功的,并且正文为空。 这个相同的空主体被初始化为 errorBody,因此你得到 null

    【讨论】:

    • 实际上,我确实看到了这一点,并在不久前完全忽略了它。但在我第二次看时,我明白你在说什么。而且由于我的body 返回内容长度为0。这就解释了null。我想问题是我的 api 没有自己返回错误代码。
    • 标记为正确,但有后续问题。 500 代码可以返回一个身体吗?我明白为什么其他代码如 4XX 可以。
    • 是的,即使是 5xx 服务器错误也应该将正文发送回客户端。您可以在 Wikipedia 页面 List of HTTP status codes 上阅读有关响应代码的更多信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    相关资源
    最近更新 更多