首页 > 解决方案 > Polly Retry 总是抛出 System.AggregateException 而不是自定义异常

问题描述

正如标题所说,我使用 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());
    }
}

这是重试 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));

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

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

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

标签: c#.netpollyretrypolicy

解决方案


在您的ExecuteAsync通话中,您不是在等待代表。
await 关键字将从AggregateException.

首选方式:

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

推荐阅读