Hi I’m new to Polly v8.
I have an API client class built using _client = new RestSharp.RestClient(...);
with methods of this form:
public async Task<TResponse> PostAsync<TRequest, TResponse>(string resource, TRequest payload) where TRequest : class
{
var request = new RestRequest(resource);
request.AddJsonBody(payload);
var response = await _client.ExecuteAsync<B2BResponse<TResponse>>(request, Method.Post);
LogAndRaiseErrors(request, response);
return response.Data.Data;
}
Here’s the LogAndRaiseErrors method:
protected void LogAndRaiseErrors(RestRequest request, RestResponse response)
{
if (response.StatusCode != HttpStatusCode.OK)
{
_logger.LogError("API Error:{response}", SerializeResponse(response));
throw new BigCommerceException(response.Content);
}
_logger.LogDebug("B2B API Call:n{response}", SerializeResponse(response));
}
I’ve had a look at the Polly documentation, but it is a bit sparse.
How would I construct a ResiliencePipeline and use it in the PostAsync
method to achieve the following goals:
- Log every request (currently done in LogAndRaiseErrorsMethod)
- Read the
response.Headers.FirstOrDefault(h=>h.Name?.ToLower() == "retry-after")?.Value
and delay for the specified seconds, which the existing code does not do at all. - Log when retries occur including the delay specified in the header.
- Move the
LogAndRaiseErrors(...)
into the Policy so the policy can deal with logging and any exceptions - Add Policy to retry for network failures/timeouts etc.