fix(client): preserve underlying status code in AutoDetect probe (#1530)
This commit is contained in:
parent
20c464c55b
commit
ba372faece
1 changed files with 295 additions and 23 deletions
|
|
@ -23,27 +23,39 @@ internal static class HttpResponseMessageExtensions
|
|||
{
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
string? responseBody = null;
|
||||
try
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
responseBody = await response.Content.ReadAsStringAsync(cts.Token).ConfigureAwait(false);
|
||||
|
||||
if (responseBody.Length > MaxResponseBodyLength)
|
||||
{
|
||||
responseBody = responseBody.Substring(0, MaxResponseBodyLength) + "...";
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore all errors reading the response body (e.g., stream closed, timeout, cancellation) - we'll throw without it.
|
||||
}
|
||||
|
||||
throw CreateHttpRequestException(response, responseBody);
|
||||
throw await CreateHttpRequestExceptionWithBodyAsync(response, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="HttpRequestException"/> for a non-success response, making a best-effort attempt to
|
||||
/// include the server's response body in the exception message so the diagnostic isn't lost.
|
||||
/// </summary>
|
||||
/// <param name="response">The non-success HTTP response message.</param>
|
||||
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
|
||||
/// <returns>An <see cref="HttpRequestException"/> with the response status and, when available, its body.</returns>
|
||||
public static async Task<HttpRequestException> CreateHttpRequestExceptionWithBodyAsync(HttpResponseMessage response, CancellationToken cancellationToken = default)
|
||||
{
|
||||
string? responseBody = null;
|
||||
try
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
responseBody = await response.Content.ReadAsStringAsync(cts.Token).ConfigureAwait(false);
|
||||
|
||||
if (responseBody.Length > MaxResponseBodyLength)
|
||||
{
|
||||
responseBody = responseBody.Substring(0, MaxResponseBodyLength) + "...";
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore all errors reading the response body (e.g., stream closed, timeout, cancellation) - we'll throw without it.
|
||||
}
|
||||
|
||||
return CreateHttpRequestException(response, responseBody);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="HttpRequestException"/> for a non-success response, including the response body in the message.
|
||||
/// </summary>
|
||||
|
|
|
|||
Loading…
Reference in a new issue