2017-10-31 8 views
0

apisまたはRetrofit2が理解できない場合がありますが、500 Internal Server Errorが届いたら、適切に通知したいと思います。rawResponseにもかかわらず、Retrofit2でerrorBody()がnullを返す

私はこのエラーを受け取った後、着信応答をログに記録するとき、私はこのようにログインしたとき、私はnullを得る:

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

私は私の応答を記録する場合しかし、私はrawResponsecodemessageなどを参照してください、

(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 
    } 
} 

S:このようなo私が理解していないのは、どこからresponse.errorBodyが引き出されるのでしょうか?

答えて

2

応答が失敗した場合、errorBodyはボディ自体に過ぎません。

これはレトロフィットのソースコードを見ることによって確認することができる - 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になります

+0

実際、私はそれを見て、それをもう少し前に完全に解除しました。しかし、私の二次的な表情で、私はあなたが言っていることを正確に見ています。そして、私の 'body'は内容の長さ0で返されているので、それはnullを説明します。私の問題は、自分のAPIがエラーコードを返さないということです。 – KickingLettuce

+0

正しいとマークされていますが、フォローアップの質問です。 500本のコードで体を元に戻すことはできますか?私はなぜ4XXのような他のコードができるのか理解しています。 – KickingLettuce

+0

はい5xxサーバーのエラーでも、本体をクライアントに送り返す必要があります。レスポンスコードの詳細については、Wikipediaの[List of HTTP status codes](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_errors)を参照してください。 –

関連する問題