C# 使用Polly时引发特定异常
我使用策略进行重试尝试的方式如下:C# 使用Polly时引发特定异常,c#,rest,polly,C#,Rest,Polly,我使用策略进行重试尝试的方式如下: results = await Policy .Handle<WebException>() .WaitAndRetryAsync ( retryCount: 5, sleepDurationProvider: retryAttempt => TimeSpan.From
results = await Policy
.Handle<WebException>()
.WaitAndRetryAsync
(
retryCount: 5,
sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
)
.ExecuteAsync(async () => await task.Invoke());
然而,我想对GUI提出一些期望。
有了这段代码,我如何防止处理特定的异常而将其抛出GUI
[更新]如果我在HandleException函数中抛出特定异常,我将在Visual Studio中收到一个未处理的错误消息对话框。以不同的方式实现,只在您希望显示给用户的异常上抛出错误,然后捕获您希望抛出的异常,并对其内容执行您想要的操作(显示给用户或不显示)
试试看
{
结果=等待策略
.Handle()
.WaitAndRetryAsync
(
retryCount:5,
sleepDurationProvider:RetryAttract=>TimeSpan.FromSeconds(Math.Pow(2,RetryAttract))
)
.ExecuteAsync(异步()=>wait task.Invoke());
}
捕获(除传送带外)
{
MessageBox.Show(例如Message);
}
公共静态类AsyncErrorHandler
{
公共静态无效句柄异常(异常ex)
{
如果(ex是例外,通过传送带)
{
投掷;
}
其他的
Debug.WriteLine(例如消息);
}
}
编辑更新
有关处理错误的帮助:但是,您发布的代码没有使用问题中引用的AsyncErrorHandler。当我收到异常时,总是调用HandleException。如果我在AsyncErrorHandler类中抛出错误,Visual Studio中将弹出一个对话框,显示错误,而不是将异常填充到GUI中。如何抛出?你只是在展示信息,还是真的在扔ex;?这就是为什么我个人只是把消息扔到一个MessageBox中,让用户看看我是否希望他们这么做。更新的答案。是的,在抛出代码后,您仍然需要处理代码中的错误!是的,我只是抛出ex,因为我想在GUI代码中特别处理它,清除一些变量。
public static class AsyncErrorHandler
{
public static void HandleException(Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
try
{
results = await Policy
.Handle<WebException>()
.WaitAndRetryAsync
(
retryCount: 5,
sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
)
.ExecuteAsync(async () => await task.Invoke());
}
catch (ExceptionToThrowToUser ex)
{
MessageBox.Show(ex.Message);
}
public static class AsyncErrorHandler
{
public static void HandleException(Exception ex)
{
if (ex is ExceptionToThrowToUser)
{
throw;
}
else
Debug.WriteLine(ex.Message);
}
}