我正在尝试使用Polly处理200 OK以外的状态代码,以便它重试API请求。
但是,我正在努力了解如何让Polly吞下一个异常然后执行重试。这是我目前拥有的,但是在语法上不正确:
var policy = Policy.HandleResult<HttpStatusCode>(r => r == HttpStatusCode.GatewayTimeout)
.Retry(5);
HttpWebResponse response;
policy.Execute(() =>
{
response = SendRequestToInitialiseApi(url);
});
在执行过程中,我需要将响应也分配给要在方法中其他位置使用的变量。
响应的返回类型是“ HttpWebResponse”,例如,当我得到“ 504”时,它将引发异常。
任何帮助/反馈将不胜感激。
干杯
提供的类型HandleResult
必须与要从执行中返回的类型相同,在您的情况下,这是一个类型,HttpWebResponse
因为您以后要使用此值。
编辑:我已经添加了山地旅行者建议的异常处理
var policy = Policy
// Handle any `HttpRequestException` that occurs during execution.
.Handle<HttpRequestException>()
// Also consider any response that doesn't have a 200 status code to be a failure.
.OrResult<HttpWebResponse>(r => r.StatusCode != HttpStatusCode.OK)
.Retry(5);
// Execute the request within the retry policy and return the `HttpWebResponse`.
var response = policy.Execute(() => SendRequestToInitialiseApi(url));
// Do something with the response.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句