I like the simplicity of EnsureSuccessStatusCode for HttpResponseMessage after a call using HttpClient. But it does not really provide great information. This is my replacement for it.
I am looking to see if I have missed useful information that is in the HttpResponseMessage, if there is a better exception type to throw or if I could generally improve it.
Some of the tricky parts was constructing a viable logging message and an exception message when logging needs it in its component parts and logging wants it all together (and some parts are optional).
public static class HttpResponseHelper
{
public static async Task CheckResponseAndThrowIfIsError(this HttpResponseMessage response,
string? errorMessage = null, ILogger? logger = null, bool includeResponseContent = true)
{
if (response.IsSuccessStatusCode == false)
{
var statusCode = response.StatusCode.ToString();
string fullErrorMessage = "";
if (!string.IsNullOrEmpty(errorMessage))
{
fullErrorMessage = $"{errorMessage}\r\n";
}
else
{
// Put in something generic so that the log as a value instead of a blank line.
errorMessage = "Call Failed";
}
fullErrorMessage += $"Call Failed with Status Code: {statusCode}";
var errorMessageFromCall = "";
if (includeResponseContent)
{
errorMessageFromCall = await response.Content.ReadAsStringAsync();
fullErrorMessage += $"\r\n{errorMessageFromCall}";
}
logger?.LogError("{errorMessage}\r\nCall Failed with Status Code: {statusCode}\r\n{errorMessageFromCall}",
errorMessage, statusCode, errorMessageFromCall);
throw new ApplicationException(fullErrorMessage);
}
}
}
Its use would look like this:
var response = await httpClient.SendAsync(message);
await response.CheckResponseAndThrowIfIsError("My Error Message Here", _logger);
CheckResponseAndThrowIfIsErroris quite a mouthful. ConsiderCheckAndMaybeThrow,ThrowIfBad,ThrowIfError. Also, rather thanfoo == falseprefer!foo. \$\endgroup\$ApplicationExceptionis too broad, perhapsHttpRequestExceptionwould be better fit here.ORlog the details, then callEnsureSuccessStatusCodeand just call it a day ! \$\endgroup\$