Reputation: 1146
I've been working with a remote web service over an unreliably and/or slow VPN that brought to light a point of failure in my code when I call a web service I will get timeout exceptions.
I did a little googling and found Polly and seemed to be exactly what I needed, but I'm still getting an unhandled TimeoutException
and would like to know what I'm doing wrong and how to update the code so that the TimeoutException
is handled, preferably using Polly.
var networkPolicy = Policy
.Handle<TimeoutException>()
.Or<CommunicationException>()
.WaitAndRetry(
5,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
(exception, timeSpan, context) =>
{
System.Diagnostics.Debug.WriteLine("Exception being retried" + exception );
});
// The following line is giving me the exception.
response = networkPolicy.Execute(() => soapClient.WebServiceFunction(request));
I'd also like to know if it is best practice to define the policy as a static readonly variable?
Upvotes: 1
Views: 1811
Reputation: 1651
Polly works so that repeated operations if an error occurs, but only a certain number of times. If the error occurs more times Polly throws it.
If you want to repeat it until when it is not thrown expetion then use RetryForever
.
Usually I use Polly with a try catch - like here:
try
{
return
await
Policy.Handle<MongoConnectionException>()
.RetryAsync(3,
(exception, i) =>
{
logger.Warn(exception,
string.Format("Mongo Connection Exception - Retry Count : {0}", i));
})
.ExecuteAsync(async () => await operation());
}
catch (MongoConnectionException ex)
{
logger.Error(ex);
return null;
}
Upvotes: 1