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.
This commit is contained in:
2026-05-19 18:57:05 +02:00
parent 71defc0e4c
commit 136c2fcb30

View File

@@ -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
/// <param name="payload">The payload to serialize.</param>
/// <returns>A <see cref="JsonContent"/> instance ready for HTTP requests.</returns>
public static JsonContent ToJsonContent<T>(T payload) => JsonContent.Create(payload);
/// <summary>
/// Throws a <see cref="ReCApiException"/> if the response indicates a non-success status code.
/// </summary>
/// <param name="response">The HTTP response to inspect.</param>
/// <param name="cancel">A token to cancel the operation.</param>
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);
}
}
}