【问题标题】:How to check status of response from Polly?如何检查 Polly 的响应状态?
【发布时间】:2020-07-17 23:41:04
【问题描述】:

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

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,但它不正确。我想做以下事情:

  • 如果由于某种原因在 x 次重试后我无法连接到 URL,那么我想返回 false 并记录它说无法与 url 对话。
  • 此外,如果我无法创建文件或无法将字节数组写入磁盘上的文件中,那么我也想返回 false。我不确定这种情况何时会发生,但我想保护我们免受这种情况的影响。在我的示例中可以实现这一点吗?

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

【问题讨论】:

  • 将其包裹在try-catch 中并在catch 语句中返回false。
  • 我想无论如何我都需要检查 Polly 的响应。不是这样吗? @aepot
  • 我对 Polly 不熟悉,但猜测如果出现问题,它必须 throw,因此您可以 catch 它。调试它(用错误的参数打破它),你会看到是否抛出了一些异常,原因是return false。

标签: c# dotnet-httpclient polly


【解决方案1】:

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

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

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
}

【讨论】:

  • 是的,但我在我的 configs 变量上看不到 Outcome 和其他属性,这就是我感到困惑的原因。我只需要弄清楚我的 URL 调用是否成功地从中获取数据。可能所有重试都失败了,所以我想避免这种情况。
  • @dragons policyResult.Outcome 你也可以检查你的policyResult.Result 是否为空。例如,您还需要哪些其他信息?
  • 是的,我理解那部分,但就我而言,我需要更改我的Policy 行吗? Bcoz 到目前为止,我无法在我的 configs 变量上获取这些属性。看起来我可能需要改变一些东西。
  • @dragons 你需要使用ExecuteAndCaptureAsync 而不是ExecuteAsync
  • 知道了。在尝试将ExecuteAsync 替换为ExecuteAndCaptureAsync 方法后出现编译错误。你认为你可以提供一个关于如何在我的例子中使用该方法的例子吗?这将帮助我更好地理解。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 1970-01-01
  • 2018-12-01
  • 2011-05-12
  • 2020-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多