如何检查 Polly 的响应状态?

How to check status of response from Polly?

我正在使用以下代码从 url 的特定文件夹中下载一个 .tgz 文件(最大 100 MB),它工作正常。我正在使用 HttpClientPolly 进行超时和重试。

private static HttpClient _httpClient = new HttpClient()
{
    Timeout = TimeSpan.FromSeconds(5)
};

private async Task<bool> Download(string fileUrl)
{
    var configs = await Policy
       .Handle<TaskCanceledException>()
       .WaitAndRetryAsync(retryCount: 3, sleepDurationProvider: i => TimeSpan.FromMilliseconds(300))
       .ExecuteAsync(async () =>
       {
           using (var httpResponse = await _httpClient.GetAsync(fileUrl).ConfigureAwait(false))
           {
               httpResponse.EnsureSuccessStatusCode();
               return await httpResponse.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
           }
       }).ConfigureAwait(false);

    File.WriteAllBytes("Testing/data.tgz", configs);
    return true;
}

正如您在上面的方法中看到的,我总是 returning 正确,但这是不正确的。我想做以下事情:

对于第一个问题 - 我正在阅读有关 Polly 的更多信息,但找不到如何在重试 x 次后检查 Polly 调用的响应,然后采取相应行动。对于第二个问题——我不确定我们如何才能做到这一点。此外,自从我最近开始使用 C#(可能几周),我可能在上面的代码中做错了,所以如果有更好的方法,请告诉我。

如果我理解你的问题,页面上有一个部分用于捕获响应

Post-执行:捕获结果,或任何最终异常

var policyResult = await Policy
              .Handle<HttpRequestException>()
              .RetryAsync()
              .ExecuteAndCaptureAsync(() => DoSomethingAsync());
/*              
policyResult.Outcome - whether the call succeeded or failed         
policyResult.FinalException - the final exception captured, will be null if the call succeeded
policyResult.ExceptionType - was the final exception an exception the policy was defined to handle (like HttpRequestException above) or an unhandled one (say Exception). Will be null if the call succeeded.
policyResult.Result - if executing a func, the result if the call succeeded or the type's default value
*/

更新

var policyResult = await Policy
   .Handle<TaskCanceledException>()
   .WaitAndRetryAsync(retryCount: 3, sleepDurationProvider: i => TimeSpan.FromMilliseconds(300))
   .ExecuteAndCaptureAsync(async () =>
   {
      using (var httpResponse = await _httpClient.GetAsync("Something").ConfigureAwait(false))
      {
         httpResponse.EnsureSuccessStatusCode();
         return await httpResponse.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
      }
   }).ConfigureAwait(false);

if (policyResult.Outcome == OutcomeType.Failure)
   return false;

try
{

    File.WriteAllBytes("Testing/data.tgz", policyResult.Result);      
    return true;
}
catch(Exception ex)
{  
    // usually you wouldn't want to catch ALL exceptions (in general), however this is updated from the comments in the chat
    // file operations can fail for lots of reasons, maybe best catch and log the results. However ill leave these details up to you
    // log the results
    return false
}