【发布时间】: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