Skip to content

Commit

Permalink
Fix missing body in raw response for error
Browse files Browse the repository at this point in the history
  • Loading branch information
Jawnnypoo authored and JakeWharton committed Jul 3, 2019
1 parent c30580d commit 06978cc
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 2 additions & 0 deletions retrofit/src/main/java/retrofit2/Response.java
Expand Up @@ -83,8 +83,10 @@ public static <T> Response<T> success(@Nullable T body, okhttp3.Response rawResp
* as the error body.
*/
public static <T> Response<T> error(int code, ResponseBody body) {
checkNotNull(body, "body == null");
if (code < 400) throw new IllegalArgumentException("code < 400: " + code);
return error(body, new okhttp3.Response.Builder() //
.body(new OkHttpCall.NoContentResponseBody(body.contentType(), body.contentLength()))
.code(code)
.message("Response.error()")
.protocol(Protocol.HTTP_1_1)
Expand Down
11 changes: 10 additions & 1 deletion retrofit/src/test/java/retrofit2/ResponseTest.java
Expand Up @@ -16,6 +16,7 @@
package retrofit2;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.ResponseBody;
import org.junit.Test;
Expand Down Expand Up @@ -119,9 +120,17 @@ public final class ResponseTest {
}

@Test public void error() {
ResponseBody errorBody = ResponseBody.create(null, "Broken!");
MediaType plainText = MediaType.get("text/plain; charset=utf-8");
ResponseBody errorBody = ResponseBody.create(plainText, "Broken!");
Response<?> response = Response.error(400, errorBody);
assertThat(response.raw()).isNotNull();
assertThat(response.raw().body().contentType()).isEqualTo(plainText);
assertThat(response.raw().body().contentLength()).isEqualTo(7);
try {
response.raw().body().source();
fail();
} catch (IllegalStateException expected) {
}
assertThat(response.code()).isEqualTo(400);
assertThat(response.message()).isEqualTo("Response.error()");
assertThat(response.headers().size()).isZero();
Expand Down

0 comments on commit 06978cc

Please sign in to comment.