From 136c2fcb302528af561a9fbc0a567275c14f0300 Mon Sep 17 00:00:00 2001 From: TekH Date: Tue, 19 May 2026 18:57:05 +0200 Subject: [PATCH] Add EnsureSuccessAsync method for HTTP error handling Introduced the `EnsureSuccessAsync` method in `ReCClientHelpers.cs` to handle HTTP response validation asynchronously. This method throws a `ReCApiException` for non-success status codes, including detailed error information such as status code, reason phrase, HTTP method, URI, and response body (if available). Updated `using` directives to support asynchronous operations and cancellation tokens. Removed redundant `#if NETFRAMEWORK` directive around `using System.Net.Http;` and adjusted `using System.Net.Http.Json;` placement for consistency. Added exception handling for response body read failures to ensure status information is still propagated. Enhanced error reporting for failed HTTP requests. --- src/ReC.Client/ReCClientHelpers.cs | 49 +++++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/src/ReC.Client/ReCClientHelpers.cs b/src/ReC.Client/ReCClientHelpers.cs index 0102710..44bc252 100644 --- a/src/ReC.Client/ReCClientHelpers.cs +++ b/src/ReC.Client/ReCClientHelpers.cs @@ -1,11 +1,10 @@ using System; using System.Globalization; using System.Linq; -using System.Net.Http.Json; - -#if NETFRAMEWORK using System.Net.Http; -#endif +using System.Net.Http.Json; +using System.Threading; +using System.Threading.Tasks; namespace ReC.Client { @@ -45,5 +44,47 @@ namespace ReC.Client /// The payload to serialize. /// A instance ready for HTTP requests. public static JsonContent ToJsonContent(T payload) => JsonContent.Create(payload); + + /// + /// Throws a if the response indicates a non-success status code. + /// + /// The HTTP response to inspect. + /// A token to cancel the operation. + public static async Task EnsureSuccessAsync(HttpResponseMessage response, CancellationToken cancel = default) + { + if (response.IsSuccessStatusCode) + return; + +#if NETFRAMEWORK + string body = null; +#else + string? body = null; +#endif + if (response.Content != null) + { + try + { +#if NETFRAMEWORK + body = await response.Content.ReadAsStringAsync().ConfigureAwait(false); +#else + body = await response.Content.ReadAsStringAsync(cancel).ConfigureAwait(false); +#endif + } + catch + { + // Swallow body read failures; status info is still propagated. + } + } + + var request = response.RequestMessage; + var method = request?.Method?.Method; + var uri = request?.RequestUri; + + var message = $"ReC API request failed with status {(int)response.StatusCode} ({response.ReasonPhrase}). " + + $"{method} {uri}" + + (string.IsNullOrWhiteSpace(body) ? string.Empty : $": {body}"); + + throw new ReCApiException(message, response.StatusCode, response.ReasonPhrase, body, method, uri); + } } }