Skip to content

Commit a1ea767

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 spring-projectsgh-33973
1 parent eee45c3 commit a1ea767

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

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

+11-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,13 @@ else if (cause instanceof IOException ioEx) {
136137
throw (message == null ? new IOException(cause) : new IOException(message, cause));
137138
}
138139
}
140+
catch (CancellationException ex) {
141+
if(timeoutHandler != null && timeoutHandler.isTimeout){
142+
throw new HttpTimeoutException("Request timed out");
143+
}
144+
Throwable cause = ex.getCause();
145+
throw new IOException(cause.getMessage(), cause);
146+
}
139147
}
140148

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

226234
private final CompletableFuture<Void> timeoutFuture;
235+
boolean isTimeout=false;
227236

228237
private TimeoutHandler(CompletableFuture<HttpResponse<InputStream>> future, Duration timeout) {
229238

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

233242
this.timeoutFuture.thenRun(() -> {
234243
if (future.cancel(true) || future.isCompletedExceptionally() || !future.isDone()) {
244+
this.isTimeout = true;
235245
return;
236246
}
237247
try {

0 commit comments

Comments
 (0)