From 36e84a5209db093ff2affd53bc7b39022f5e9ba7 Mon Sep 17 00:00:00 2001 From: Jonatan Ivanov Date: Wed, 7 Aug 2024 16:33:29 -0700 Subject: [PATCH] Fix RestClient instrumentation ClientHttpResponse implements Closeable and the close method of DefaultConvertibleClientHttpResponse also stops the current Observation. Before this change exiting the try-with-resource block stopped the Observation since it called close on ClientHttpResponse. After this, there were multiple error and stop calls on the Observation in the catch blocks after the Observation was already stopped which is invalid. This change reorders the flow by stopping the Observation in the finally block (closing ClientHttpResponse) and not stopping the Observation in any of the catch blocks. Closes gh-33346 --- .../org/springframework/web/client/DefaultRestClient.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java b/spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java index c9e4681a92..0e89d86692 100644 --- a/spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java +++ b/spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java @@ -196,7 +196,7 @@ final class DefaultRestClient implements RestClient { MediaType contentType = getContentType(clientResponse); - try (clientResponse) { + try { callback.run(); IntrospectingClientHttpResponse responseWrapper = new IntrospectingClientHttpResponse(clientResponse); @@ -240,17 +240,18 @@ final class DefaultRestClient implements RestClient { ResolvableType.forType(bodyType) + "] and content type [" + contentType + "]", cause); if (observation != null) { observation.error(restClientException); - observation.stop(); } throw restClientException; } catch (RestClientException restClientException) { if (observation != null) { observation.error(restClientException); - observation.stop(); } throw restClientException; } + finally { + clientResponse.close(); + } } private static MediaType getContentType(ClientHttpResponse clientResponse) {