Skip to content

Commit a8e3ac0

Browse files
committed
Return response body in FeignException from errorReading (#2618)
FeignException.errorReading passed request.body() and request.headers() into the constructor's responseBody/responseHeaders parameters, so FeignException.responseBody()/contentUTF8()/responseHeaders() exposed the request data instead of the response when a read failure occurred while decoding a response. Read the response body (mirroring errorStatus, tolerating a streamed or already-consumed body) and pass the response headers instead. Signed-off-by: seonwoo_jung <79202163+seonwooj0810@users.noreply.github.com>
1 parent 5dbc552 commit a8e3ac0

2 files changed

Lines changed: 15 additions & 2 deletions

File tree

core/src/main/java/feign/FeignException.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,13 +177,20 @@ public String contentUTF8() {
177177
}
178178

179179
static FeignException errorReading(Request request, Response response, IOException cause) {
180+
byte[] body = {};
181+
try {
182+
if (response.body() != null) {
183+
body = Util.toByteArray(response.body().asInputStream());
184+
}
185+
} catch (IOException ignored) { // NOPMD
186+
}
180187
return new FeignException(
181188
response.status(),
182189
format("%s reading %s %s", cause.getMessage(), request.httpMethod(), request.url()),
183190
request,
184191
cause,
185-
request.body(),
186-
request.headers());
192+
body,
193+
response.headers());
187194
}
188195

189196
public static FeignException errorStatus(String methodKey, Response response) {

core/src/test/java/feign/FeignExceptionTest.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,22 @@ void canCreateWithRequestAndResponse() {
4343
StandardCharsets.UTF_8,
4444
null);
4545

46+
Map<String, Collection<String>> responseHeaders =
47+
Collections.singletonMap("content-type", Collections.singletonList("application/json"));
4648
Response response =
4749
Response.builder()
4850
.status(400)
4951
.body("response".getBytes(StandardCharsets.UTF_8))
52+
.headers(responseHeaders)
5053
.request(request)
5154
.build();
5255

5356
FeignException exception =
5457
FeignException.errorReading(request, response, new IOException("socket closed"));
5558
assertThat(exception.responseBody()).isNotEmpty();
59+
// the exception must carry the response body, not the request body (gh-2618)
60+
assertThat(exception.contentUTF8()).isEqualTo("response");
61+
assertThat(exception.responseHeaders()).containsKeys("content-type");
5662
assertThat(exception.hasRequest()).isTrue();
5763
assertThat(exception.request()).isNotNull();
5864
}

0 commit comments

Comments
 (0)