[英]Use Polly to retry api request if the status code is not equal to 200 OK
I am trying to use Polly to handle status codes other than 200 OK so that it retries the API request.我正在尝试使用 Polly 处理 200 OK 以外的状态代码,以便它重试 API 请求。
However, I am struggling to understand how to Polly to swallow an exception and then execute a retry.但是,我很难理解如何让 Polly 吞下异常然后执行重试。 This is what I currently have, but it is not syntactically correct:
这是我目前拥有的,但在语法上不正确:
var policy = Policy.HandleResult<HttpStatusCode>(r => r == HttpStatusCode.GatewayTimeout)
.Retry(5);
HttpWebResponse response;
policy.Execute(() =>
{
response = SendRequestToInitialiseApi(url);
});
In the execution, I need the response to also be assigned to a variable to be used elsewhere in the method.在执行过程中,我需要将响应分配给一个变量,以便在方法的其他地方使用。
The return type of the response is a 'HttpWebResponse' and when I get a '504' for instance, it throws an exception.响应的返回类型是“HttpWebResponse”,例如,当我得到“504”时,它会引发异常。
Any help/feedback would be appreciated.任何帮助/反馈将不胜感激。
Cheers干杯
The type you provide to HandleResult
must be the same type you want to return from the execution, which in your case is an HttpWebResponse
since you want to make use of this value later.您提供给
HandleResult
的类型必须与您希望从执行中返回的类型相同,在您的情况下是HttpWebResponse
因为您想稍后使用此值。
Edit: I've added in exception handling as suggested by mountain traveller编辑:我已经按照山地旅行者的建议添加了异常处理
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.