c# - 如何检查 Polly 的响应状态?
问题描述
我正在.tgz
使用以下代码从 url 下载特定文件夹中的文件(最大 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#(可能是几周),我可能在上面的代码中做错了,所以如果有更好的方法,请告诉我。
解决方案
如果我理解您的问题,页面上有一个部分表示捕获响应
执行后:捕获结果或任何最终异常
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
}
推荐阅读
- python - 如何在 x 轴上仅显示可用值
- php - 将 hex/hsl 值映射到颜色范围
- azure-devops - 在矩阵构建中使用 Build.ArtifactStagingDirectory 和 PublishPipelineArtifact
- android - 片段中的空参数捆绑
- javascript - javascript/typescript 中的代码缩减/可重用性技术
- java - 将对象列表转换为地图
> - c - 当我的角色是“*”或“/”时,这个循环不应该停止吗?
- php - 发布与页面链接 php 冲突的蛞蝓
- reactjs - 浅不渲染包装的组件
- python - 如何修复python中的错误:名称错误:未定义名称