Skip to content

Commit 2c2e43d

Browse files
Copilotstephentoub
andcommitted
Add 5-second timeout when reading error response body
Prevents hanging in edge cases where server sends error response but doesn't end the request. Linked CancellationTokenSource ensures the original cancellation token is still honored. Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
1 parent c3d93aa commit 2c2e43d

1 file changed

Lines changed: 7 additions & 4 deletions

File tree

src/Common/HttpResponseMessageExtensions.cs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,15 @@ public static async Task EnsureSuccessStatusCodeWithResponseBodyAsync(this HttpR
2424
string? responseBody = null;
2525
try
2626
{
27-
responseBody = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
27+
// Add a timeout to prevent hanging if the server sends an error response but doesn't end the request.
28+
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
29+
cts.CancelAfter(TimeSpan.FromSeconds(5));
30+
responseBody = await response.Content.ReadAsStringAsync(cts.Token).ConfigureAwait(false);
2831
}
29-
catch (Exception ex) when (ex is not OperationCanceledException)
32+
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
3033
{
31-
// Ignore errors reading the response body (e.g., stream closed) - we'll throw without it.
32-
// Allow cancellation exceptions to propagate.
34+
// Ignore errors reading the response body (e.g., stream closed, timeout) - we'll throw without it.
35+
// Allow cancellation exceptions to propagate only if the original token was cancelled.
3336
}
3437

3538
throw CreateHttpRequestException(response, responseBody);

0 commit comments

Comments
 (0)