Right method to Use Polly C# Library to handle Exception

12,481

Solution 1

It is easy, basically you need to define the policy and passing the call back later is just as simple . Check this article which describes how to accomplish exactly what you want in details.

Basically, you can define your policy as follows :

async Task<HttpResponseMessage> QueryCurrencyServiceWithRetryPolicy(Func<Task<HttpResponseMessage>> action)
    {
        int numberOfTimesToRetry = 7;
        int retryMultiple = 2;

        //Handle HttpRequestException when it occures
        var response = await Policy.Handle<HttpRequestException>(ex =>
        {
            Debug.WriteLine("Request failed due to connectivity issues.");
            return true;
        })

        //wait for a given number of seconds which increases after each retry
        .WaitAndRetryAsync(numberOfTimesToRetry, retryCount => TimeSpan.FromSeconds(retryCount * retryMultiple))

        //After the retry, Execute the appropriate set of instructions
        .ExecuteAsync(async () => await action());

        //Return the response message gotten from the http client call.
        return response;
    }

And you can pass the callback as follows:

var response = await QueryCurrencyServiceWithRetryPolicy(() => _httpClient.GetAsync(ALL_CURRENCIES_URL));

Solution 2

I think what you are after is ExecuteAndCapture instead of Execute:

generalExceptionPolicy.ExecuteAndCapture(() => DoSomething());

Check this out for more details.

Share:
12,481
Sreeraj
Author by

Sreeraj

Passionate Mobile &amp; Web Developer, speaker, open-source contributor... Loves C#, Swift, iOS, Xamarin, Asp.Net, ReactJS. Co-founder of Xhackers-Kerala. SOReadyToHelp.

Updated on June 04, 2022

Comments

  • Sreeraj
    Sreeraj almost 2 years

    I am trying to use Polly to handle exceptions thrown by my WebRequest.

    This is my implementation.

    var generalExceptionPolicy=Policy.Handle<Exception>().WaitAndRetry(2, retryAttempt => 
                        TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),(exception,timespan)=>{
    
            if(attempt++ == 2)
            {
                Toast.MakeText(Activity,"No Connection Bro",ToastLength.Short).Show();
    
    
            }
        });
       var test = await generalExceptionPolicy.ExecuteAsync(()=>PostPreLogin (view.FindViewById<EditText> (Resource.Id.mobileTextBox).Text));
    

    I have got the retries working. But what I am wondering is where will I get a callback after the last attempt ? I am getting a callback in Policy definition part, where I am trying to display a Toastmessage. But that is only between the trials. I am not getting it after my last trial.

    Also, my UI freezes after the last trial. Maybe becuase ExecuteAsync Task did not complete, due to the Exception. If that is so, what is the right approach to use Polly library ?

    This is the method that I am trying to handle with Polly

    public  async Task<string> PostPreLogin(string userName)
        {
            var preloginvalue = await Account.PreLoginPost (userName);
            return preloginvalue;
    
        }