I am implementing a retry pattern for Http requests in C# using Polly.
This is the code I am using
return Policy<HttpResponseMessage>
.Handle<HttpRequestException>()
.OrTransientHttpStatusCode()
.OrAdditionalTransientHttpStatusCode()
.Or<TimeoutRejectedException>()
.WaitAndRetryAsync(
retryCount: configuration.MaxRetries,
sleepDurationProvider: (retryIndex, result, context) =>
{
if (result.Result is { StatusCode: HttpStatusCode.ServiceUnavailable })
return some wait time
if (result.Result is { StatusCode: HttpStatusCode.TooManyRequests } ||
result.Result is { StatusCode: HttpStatusCode.Forbidden})
return some wait time
return some wait time
},
onRetryAsync: (result, span, retryIndex, context) =>
{
string requestUrl = result.Result?.RequestMessage?.RequestUri?.AbsoluteUri ?? string.Empty;
_logger.LogWarning("Transient type: {type} ; Retry index: {index}; Span: {seconds}; Uri: {uri}", type, retryIndex, span.TotalSeconds, requestUrl);
return Task.CompletedTask;
});
When the TimeoutRejectedException
is triggered, result.Result
parameter received in the onRetryAsync
method is null, and the result.Exception
stores the timeout exception data. In this Exception there is not any information about the endpoint that led to the timeout. As a result, the logging does not have the requestUrl
populated.
This is how this is set up for a named HttpClient in the Startup
services
.AddHttpClient("#id")
.AddPolicyHandler((sp, _) => new PolicyFactory(sp.GetRequiredService<ILogger<PolicyFactory>>()).Create())
Is there any way that I can set up my policy so that the incoming data provides such information? I want this defined policy to be associated to several named clients (thus the factory), but that the setting and logging is detailed with the values for each incoming request.