Skip to content

Commit

Permalink
Copy headers map in RestClientResponseException to ensure serializabi…
Browse files Browse the repository at this point in the history
…lity

This commit ensures that the HttpHeaders used are serializable by making
 a copy.

Closes gh-31787
  • Loading branch information
poutsma committed Dec 11, 2023
1 parent 7432a96 commit 57b8100
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import org.springframework.http.HttpStatusCode;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

/**
* Common base class for exceptions that contain actual HTTP response data.
Expand Down Expand Up @@ -88,11 +90,27 @@ public RestClientResponseException(
super(message);
this.statusCode = statusCode;
this.statusText = statusText;
this.responseHeaders = headers;
this.responseHeaders = copyHeaders(headers);
this.responseBody = (responseBody != null ? responseBody : new byte[0]);
this.responseCharset = (responseCharset != null ? responseCharset.name() : null);
}

/**
* Copies the given headers, because the backing map might not be
* serializable.
*/
@Nullable
private static HttpHeaders copyHeaders(@Nullable HttpHeaders headers) {
if (headers != null) {
MultiValueMap<String, String> result = new LinkedMultiValueMap<>(headers.size());
headers.forEach((name, values) -> values.forEach(value -> result.add(name, value)));
return HttpHeaders.readOnlyHttpHeaders(result);
}
else {
return null;
}
}


/**
* Return the HTTP status code.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public void handleError() throws Exception {
assertThatExceptionOfType(HttpClientErrorException.class)
.isThrownBy(() -> handler.handleError(response))
.withMessage("404 Not Found: \"Hello World\"")
.satisfies(ex -> assertThat(ex.getResponseHeaders()).isSameAs(headers));
.satisfies(ex -> assertThat(ex.getResponseHeaders()).isEqualTo(headers));
}

@Test
Expand Down

0 comments on commit 57b8100

Please sign in to comment.