[英]Enter a Catch Method in WaitAndRetryAsync
目標:
如果你已經嘗試了第三次,但它沒有成功。 然后你想使用另一種方法。
我想防止顯示錯誤消息網頁。
問題:
是否可以在 WaitAndRetryAsync 中輸入與 catch 方法類似的方法?
RetryPolicy<HttpResponseMesssage> httpWaitAndRetryPolicy = Policy
.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.WaitAndRetryAsync
(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2. retryAttempt)/2));
謝謝!
您可以在策略上使用ExecuteAsync
,然后使用ContinueWith
來處理最終響應,如下所示:
RetryPolicy<HttpResponseMessage>
.Handle<HttpRequestException>()
.Or<TaskCanceledException>()
.WaitAndRetryAsync
(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt) / 2))
.ExecuteAsync(() =>
{
//do stuff that you want retry
}).ContinueWith(x =>
{
if (x.Exception != null)
{
//means exception raised during execute and handle it
}
// return your HttpResponseMessage
}, scheduler: TaskScheduler.Default);
遵循@TheodorZoulias 的評論,使用ContinueWith
的最佳實踐是將TaskScheduler
顯式設置為默認值,因為ContinueWith
將調度程序更改為Current
並可能導致死鎖。
首先, WaitAndRetryAsync
返回AsyncRetryPolicy<T>
,而不是RetryPolicy<T>
,這意味着您發布的代碼無法編譯。
在 polly 的情況下,策略的定義和該策略的執行是分開的。 因此,首先您定義一個策略(或策略的混合),然后在需要時執行它。
AsyncRetryPolicy<HttpResponseMessage> retryInCaseOfNotSuccessResponsePolicy = Policy
.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.WaitAndRetryAsync
(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2.retryAttempt) / 2));
HttpResponseMessage serviceResponse = null;
try
{
serviceResponse = await retryInCaseOfNotSuccessResponsePolicy.ExecuteAsync(
async ct => await httpClient.GetAsync(resourceUri, ct), default);
}
catch (Exception ex)
when(ex is HttpRequestException || ex is OperationCanceledException)
{
//TODO: log
}
if (serviceResponse == null)
{
//TODO: log
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.