当我知道代码针对 429 问题遇到 WebException 的事实时,有人可以建议为什么我的 Policy 句柄没有处理我的 WebException 错误吗?我已经研究了一段时间,需要一些帮助。
这是我的 Polly 政策:
return Policy.Handle<WebException>() .WaitAndRetry(15, // We can also do this with WaitAndRetryForever... but chose WaitAndRetry this time. attempt => TimeSpan.FromSeconds(0.1 * Math.Pow(2, attempt)), // Back off! 2, 4, 8, 16 etc times 1/4-second (exception, calculatedWaitDuration) => // Capture some info for logging! if needed { // This is your new exception handler! Debug.WriteLine("Retry count: " + retries++); Debug.WriteLine("Wait Duration: " + calculatedWaitDuration); });
我这样使用它:
webResponseWaitRetryPolicy.Execute(() =>
{
// Make a request and get a response
UriBuilder builder = new UriBuilder(options.BaseUrl);
builder.Port = -1;
var query = HttpUtility.ParseQueryString(builder.Query);
/// handle parameters
query["client_key"] = options.ClientKey;
query["model_id"] = model;
query["image_url"] = imageUrl;
builder.Query = query.ToString();
string url = builder.ToString();
string content = string.Empty;
Result objResult;
HttpWebResponse response = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
try
{
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
content = reader.ReadToEnd();
}
objResult = JsonConvert.DeserializeObject<Result>(content);
}
catch(WebException ex)
{
eventualFailures++;
Debug.WriteLine("Failure: " + eventualFailures);
}
});
return objResult;
}
当我运行代码时,我可以看到它触发了 WebException,但没有调用 Policy。请帮忙。