首页 > 解决方案 > 如何检查 Polly 的响应状态?

问题描述

我正在.tgz使用以下代码从 url 下载特定文件夹中的文件(最大 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;
}

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

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

标签: c#dotnet-httpclientpolly

解决方案


如果我理解您的问题,页面上有一个部分表示捕获响应

执行后:捕获结果或任何最终异常

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
}

推荐阅读