Polly Retry总是抛出System.AggregateException而不是自定义异常

时间:2020-06-10 13:55:25

标签: c# .net polly retrypolicy

正如标题所述,我使用Polly创建了重试机制。问题是我总是得到System.AggregateException而不是自己的自定义异常。我将在此处添加代码。

这是我创建的polly静态类:

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());
    }
}

这是重试波莉的实际呼叫:

   var result= await PollyExtension.RetryRequestWithPolicyAsync<int, CustomException>( () =>
        {
            if (1 + 1 == 2)
            {
                throw new MyException("test");
            }
            else
            {
                throw new CustomException("test");
            }
        },
       1,
        TimeSpan.FromSeconds(1));

我的期望是,如果我抛出MyException,那么polly也将MyException抛出给调用方方法。相反,抛出的异常是System.AggregateException。

我在这里做错了什么?谢谢

编辑1:经过更多调试后,似乎AggregateException具有内部异常MyException。这是预期的行为还是我做错了什么?

1 个答案:

答案 0 :(得分:1)

在您的ExecuteAsync电话中,您不等待代表。
关键字await将从AggregateException中解开您的自定义异常。

首选方式:

.ExecuteAsync(async () => await customAction?.Invoke());