【问题标题】:Polly Retry always throws System.AggregateException instead of custom exceptionPolly Retry 总是抛出 System.AggregateException 而不是自定义异常
【发布时间】:2020-06-10 13:55:25
【问题描述】:

正如标题所说,我使用 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。这是预期的行为还是我做错了什么?

【问题讨论】:

  • 我无法使用您发布的代码重现此问题。运行此代码时,我根本看不到 AggregateException
  • 查看本文中关于使用 AggregateException 的备注部分:docs.microsoft.com/en-us/dotnet/api/… 下面你会找到处理自己的异常的方法。

标签: c# .net polly retrypolicy


【解决方案1】:

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

首选方式:

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

【讨论】:

  • 这确实有帮助。我真的很想念那个。谢谢@Peter Csala
  • 嗨@cozmin-calin 我很高兴这个“技巧”帮助了你。你能把这篇文章标记为答案吗?提前致谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 2012-09-18
  • 2018-07-09
  • 2016-02-24
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
相关资源
最近更新 更多