As the title says, I created a retry mechanism using Polly. The problem is that I always get a System.AggregateException instead of my own custom exception. I will add the code here.
This is the polly static class which I created:
public static class PollyExtension
{
public static Task<T> RetryRequestWithPolicyAsync<T,T1>(
Func<Task<T>> customAction,
int retryCount,
TimeSpan pauseSecondsBetweenFailures) where T1 : Exception
{
return
Policy
.Handle<T1>()
.WaitAndRetryAsync(retryCount, i => pauseSecondsBetweenFailures).ExecuteAsync(() => customAction?.Invoke());
}
}
Here is that actuall call of the retry polly:
var result= await PollyExtension.RetryRequestWithPolicyAsync<int, CustomException>( () =>
{
if (1 + 1 == 2)
{
throw new MyException("test");
}
else
{
throw new CustomException("test");
}
},
1,
TimeSpan.FromSeconds(1));
My expectations are that if I throw MyException then, polly will also throw MyException to the caller method. Instead the exception thrown is System.AggregateException.
What I am doing wrong here ? Thanks
EDIT 1: after more debug it seems that AggregateException has as inner exception MyException. Is this intended behaviour or I am doing something wrong ?
In your ExecuteAsync
call you are not awaiting the delegate.
The await keyword would unwrap your custom exception from the AggregateException
.
Preferred way:
.ExecuteAsync(async () => await customAction?.Invoke());