3

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 ?

cozmin-calin
  • 421
  • 2
  • 6
  • 19
  • I'm unable to repro this with the code you posted. I don't see an `AggregateException` at all when I run this code. – Stephen Cleary Jun 10 '20 at 15:37
  • Check the remarks section about the use of the AggregateException in this article: https://learn.microsoft.com/en-us/dotnet/api/system.aggregateexception?view=netcore-3.1 Below you will find a way to handle your own exception. – Silviu Antochi Jun 11 '20 at 14:27

1 Answers1

1

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());
Peter Csala
  • 17,736
  • 16
  • 35
  • 75