Polly: WaitAndRetryAsync中是否有任何方式/方法可以被视为RetryCompleted?<



我有一个查询-你可以帮助我,如果已经完成了WaitAndRetryAsync中的数字RetryCount,但仍然没有得到StatusCode.OK。然后我想通过异常。那么我该怎么做呢?

或者有什么方法如果号码或重试计数完成,那么有什么方法可以提供功能OnRetryComplete,这样我们可以给任何消息我们重试多次,但不能得到成功的代码,可以返回任何方法。

var policy = Policy
.Handle<Exception>()
.OrResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.WaitAndRetryAsync(2, _ => TimeSpan.FromMilliseconds(200));
try
{
int count = 0;
var responseMessage = await asyncPolicy.ExecuteAsync(async () =>
{
string requestJson = JsonSerializer.Serialize(eligRequest, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
using var content = new StringContent(requestJson, Encoding.UTF8, "application/json");
HttpResponseMessage result = await httpClient.PostAsync("test/api/ate", content);
return result.EnsureSuccessStatusCode();
});
return responseMessage;
}
catch (HttpRequestException error)
{
logger.LogError(error);
throw new CustomException();
}

如果不能在给定的重试次数和时间内完成操作,Polly将抛出该异常。

public async Task Main()
{
var httpClient = new HttpClient();
AsyncRetryPolicy _retryPolicy;
_retryPolicy = Policy.Handle<Exception>()
.WaitAndRetryAsync(2, retryAttempt =>
{
Console.WriteLine("Attempt... " + retryAttempt);
var timeToRetry = TimeSpan.FromSeconds(2);
Console.WriteLine($"Waiting {timeToRetry.TotalSeconds} seconds");
return timeToRetry;
});
try
{
await _retryPolicy.ExecuteAsync(async () =>
{
var response = await httpClient.GetAsync("https://urlnotexist.com/api/products/1");
response.EnsureSuccessStatusCode();
});
}
catch (Exception ex)
{
Console.WriteLine("Final Throw");
//Validate your logic here and throw ex.
}
}

以上代码将生成如下输出:

Attempt... 1
Waiting 2 seconds
Attempt... 2
Waiting 2 seconds
Final Throw

因此在catch块中,您将获得异常。从那里,你可以验证你的逻辑,并进一步抛出它或记录它。

我想你正在寻找ExecuteAndCaptureAsync和PolicyResult。

PolicyResult公开了几个有用的属性来处理抛出的异常:

  • Outcome:如果所有重试都失败而没有成功,则为Failure
  • FinalException:由修饰代码
  • 抛出的原始异常
PolicyResult<string> result = await policy.ExecuteAndCaptureAsync(async () => await ...);
if(result.Outcome == OutcomeType.Failure && result.FinalException != null)
{
throw new CustomException();
}

还请更改您的策略,以表明如果成功,您希望返回一个字符串:

var policy = Policy<string>
.Handle<Exception>()
.OrResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.WaitAndRetryAsync(2, _ => TimeSpan.FromMilliseconds(200));

此代码工作正常,我已粘贴在我的问题。很抱歉给您带来不便。

谢谢大家的努力。

相关内容

最新更新