Skip to content

Commit 1717ef7

Browse files
committed
Fix throws only ResourceAccessException on timeout
CancellationExceptions are thrown instead of the expected ResourceAccessException during timeout scenarios. Handle the CancellationExceptions in order to throw an ResourceAccessException when timeout occurred Closes gh-33973 Signed-off-by: giampaolo <giampaorr@gmail.com>
1 parent eee45c3 commit 1717ef7

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

spring-web/src/main/java/org/springframework/http/client/JdkClientHttpRequest.java

+7-1
Original file line numberDiff line numberDiff line change
@@ -96,12 +96,13 @@ public URI getURI() {
9696
@Override
9797
protected ClientHttpResponse executeInternal(HttpHeaders headers, @Nullable Body body) throws IOException {
9898
CompletableFuture<HttpResponse<InputStream>> responseFuture = null;
99+
TimeoutHandler timeoutHandler = null;
99100
try {
100101
HttpRequest request = buildRequest(headers, body);
101102
responseFuture = this.httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream());
102103

103104
if (this.timeout != null) {
104-
TimeoutHandler timeoutHandler = new TimeoutHandler(responseFuture, this.timeout);
105+
timeoutHandler = new TimeoutHandler(responseFuture, this.timeout);
105106
HttpResponse<InputStream> response = responseFuture.get();
106107
InputStream inputStream = timeoutHandler.wrapInputStream(response);
107108
return new JdkClientHttpResponse(response, inputStream);
@@ -136,6 +137,9 @@ else if (cause instanceof IOException ioEx) {
136137
throw (message == null ? new IOException(cause) : new IOException(message, cause));
137138
}
138139
}
140+
catch (CancellationException ex) {
141+
throw new HttpTimeoutException("Request timed out");
142+
}
139143
}
140144

141145
private HttpRequest buildRequest(HttpHeaders headers, @Nullable Body body) {
@@ -224,6 +228,7 @@ public ByteBuffer map(byte[] b, int off, int len) {
224228
private static final class TimeoutHandler {
225229

226230
private final CompletableFuture<Void> timeoutFuture;
231+
private boolean isTimeout=false;
227232

228233
private TimeoutHandler(CompletableFuture<HttpResponse<InputStream>> future, Duration timeout) {
229234

@@ -232,6 +237,7 @@ private TimeoutHandler(CompletableFuture<HttpResponse<InputStream>> future, Dura
232237

233238
this.timeoutFuture.thenRun(() -> {
234239
if (future.cancel(true) || future.isCompletedExceptionally() || !future.isDone()) {
240+
this.isTimeout = true;
235241
return;
236242
}
237243
try {

0 commit comments

Comments
 (0)