Search code examples
c#restpolly

Throwing specific exception when using Polly


I am using polly policy for retry attempts in the following way:

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

I am using the AsyncErrorHandler to handle all the web exceptions:

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

However some of the expections I would like to throw up to the GUI. With this code in place how can I prevent handling of a specific exception and instead throw it to the GUI?

[UPDATE] If I throw a specific exception inside the HandleException function I receive an Unhandled Error Message dialog in Visual Studio.


Solution

  • Implement it differently to only throw errors on the ones you want displayed to a user, then catch those you want to throw and do what you want with their contents (either show to user or not).

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

    Editted for update.

    For help handling errors: Best practices for catching and re-throwing .NET exceptions