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

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

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

但是,当我记录响应时,在code内看到messagerawResponse等,如下所示:

(为简便起见,删除了一些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从哪里开始绘制?

最佳答案

对于失败的响应,errorBody只是 body 本身。

可以通过查看改造源代码-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

关于android - 尽管有rawResponse,errorBody()在Retrofit2中仍返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47041955/

10-08 23:59