gpt4 book ai didi

c# - 使用 Polly 时抛出特定异常

转载 作者:行者123 更新时间:2023-11-30 16:51:17 25 4
gpt4 key购买 nike

我正在使用 polly以下列重试策略:

results = await Policy
.Handle<WebException>()
.WaitAndRetryAsync
(
retryCount: 5,
sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
)
.ExecuteAsync(async () => await task.Invoke());

我正在使用 AsyncErrorHandler处理所有网络异常:

public static class AsyncErrorHandler
{
public static void HandleException(Exception ex)
{
Debug.WriteLine(ex.Message);
}
}

但是我想对 GUI 提出一些期望。有了这段代码,我如何才能阻止处理特定异常并将其抛给 GUI?

[更新] 如果我在 HandleException 函数中抛出一个特定的异常,我会在 Visual Studio 中收到一个未处理的错误消息对话框。

最佳答案

以不同的方式实现它,只在您想要向用户显示的那些错误上抛出错误,然后捕获您想要抛出的错误并根据其内容执行您想要的操作(向用户显示或不显示)。

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

编辑更新。

有关处理错误的帮助:Best practices for catching and re-throwing .NET exceptions

关于c# - 使用 Polly 时抛出特定异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34029931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com