我想使用Polly处理我需要进行的HTTP API调用的结果。我的政策定义为:
var r = await Policy
.HandleResult<DescribeApplicationVersionsResponse>(x => x.ApplicationVersions[0]?.Status != ApplicationVersionStatus.Processed)
.WaitAndRetryAsync(10, retryAttempt => TimeSpan.FromSeconds(1), onRetry: (describeResponse, timeSpan, context) => {
Console.WriteLine($"Application version was '{describeResponse.Result.ApplicationVersions[0].Status}', retrying in {timeSpan}");
})
.ExecuteAsync(() =>
BeanstalkClient.DescribeApplicationVersionsAsync(describeApplicationVersionRequest)
);
如果该策略永远不会成功(即,永远不会满足结果标准并且已经通过了重试限制),我想抛出一个异常,因为我的应用程序无法继续。
是否可以通过Polly策略构建器扩展方法进行定义?
答案 0 :(得分:2)
如果为Polly重试策略配置的所有重试均已用尽而未成功执行委托,则重试策略将抛出不允许再试的异常,如in the Polly readme(重试脚部分)和{{ 3}}。
如果要抛出与委托传播不同的异常,则可以执行以下任一操作:
try
/ catch
并扔其他东西; (或).ExecuteAndCapture(...)
将PolicyWrap
包装在重试策略之外,并在FallbackPolicy中处理重试失败的异常,并在fallback操作中重新抛出另一个自定义异常。 已编辑:要反映出OP的原始政策是在处理结果,而不是例外。将FallbackPolicy
与PolicyWrap
结合使用的方法可能如下:
var retry = Policy
.HandleResult<DescribeApplicationVersionsResponse>(x => x.ApplicationVersions[0]?.Status != ApplicationVersionStatus.Processed)
.WaitAndRetryAsync(10, retryAttempt => TimeSpan.FromSeconds(1), onRetry: (describeResponse, timeSpan, context) => {
Console.WriteLine($"Application version was '{describeResponse.Result.ApplicationVersions[0].Status}', retrying in {timeSpan}");
});
var fallback = Policy
.HandleResult<DescribeApplicationVersionsResponse>(x => x.ApplicationVersions[0]?.Status != ApplicationVersionStatus.Processed) // Probably worth factoring the predicate out into a method so that it is only stated once.
.FallbackAsync(async () => { throw new ReplacementException(); });
var r = await fallback.WrapAsync(retry)
.ExecuteAsync(() =>
BeanstalkClient.DescribeApplicationVersionsAsync(describeApplicationVersionRequest)
);