Successfully added
.NET
by Patrik
How to Log HTTP Failures Across Multiple Exception Types
Issue
HTTP calls fail for many reasons: timeouts, throttling, network issues, or retry exhaustion. Logging only one exception type results in missing or inconsistent diagnostic information.
Cause
Most implementations log only HttpRequestException, ignoring other relevant exceptions like retry errors or cancellation events. Over time, this makes troubleshooting difficult and logs incomplete.
Resolution
Use a single unified logging method that handles all relevant exception types. Apply specific messages for each category while keeping the logic in one place.
private void LogServiceException(Exception ex)
{
switch (ex)
{
case HttpRequestException httpEx:
LogHttpRequestException(httpEx);
break;
case RetryException retryEx:
_logger.LogError("Retry exhausted. Last status: {Status}. Exception: {Ex}",
retryEx.StatusCode, retryEx);
break;
case TaskCanceledException:
_logger.LogError("Request timed out. Exception: {Ex}", ex);
break;
case OperationCanceledException:
_logger.LogError("Operation was cancelled. Exception: {Ex}", ex);
break;
default:
_logger.LogError("Unexpected error occurred. Exception: {Ex}", ex);
break;
}
}
private void LogHttpRequestException(HttpRequestException ex)
{
if (ex.StatusCode == HttpStatusCode.NotFound)
_logger.LogError("Resource not found. Exception: {Ex}", ex);
else if (ex.StatusCode == HttpStatusCode.TooManyRequests)
_logger.LogError("Request throttled. Exception: {Ex}", ex);
else
_logger.LogError("HTTP request failed ({Status}). Exception: {Ex}",
ex.StatusCode, ex);
}
Centralizing logic ensures consistent, clear, and maintainable logging across all error paths.
logging
diagnostics
httpclient
dotnet
monitoring
Referenced in:
Comments