使用Polly时引发特定异常

本文关键字:异常 Polly 使用 | 更新日期: 2023-09-27 18:25:19

我使用polly策略以以下方式重试:

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

我正在使用AsyncErrorHandler来处理所有的web异常:

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

然而,我想向GUI提出一些期望。有了这些代码,我如何防止处理特定的异常,而将其抛出GUI?

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

使用Polly时引发特定异常

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

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

已编辑以进行更新。

有关处理错误的帮助:捕获和重新抛出.NET异常的最佳实践