Polly : A latest nuget package for Exception handling

We all know that every applications sometime or other gives exception.

Have you ever wondered wish you could give Retry, Retry Forever or Wait and Retry on your particular exception? Well we have already a nuget package for that which is called Polly.

Polly is a .NET 3.5 / 4.0 / 4.5 / PCL library that allows developers to express transient exception handling policies such as Retry, Retry Forever, Wait and Retry or Circuit Breaker in a fluent manner.

First of all we will see how to install Polly. Well there is not any rocket science for it and we will simply do it as we install other nugget packages as shown below :-

Install-Package Polly

Now I will summarise what facilities Polly provides us.

Handling exceptions :-

Handling exceptions can be a hassle sometimes. Not just setting the try/catches up, but deciding on the policy for the catch can make the exception management code more complex than the method itself!

So in Polly we can simply handle the exception as shown below :-


Policy.Handle<ArgumentNullException>();


and if you want to handle more exceptions then simply add .Or as shown below :-


Policy.Handle<ArgumentNullException>().Or<DivideByZeroException>();


Now suppose you want to handle only particular parameter for handling null exception then simply write :-

Policy.Handle<ArgumentNullException>(ex => ex.ParamName == "test");

Retry :-
Suppose you are in need where we want to give try to your code for more than one time not to fall in exception then here is the solution.

// Retry once
Policy.Handle<ArgumentNullException>().Retry();// Retry multiple times
Policy.Handle<ArgumentNullException>().Retry(3);

Now suppose you want to Retry multiple times, calling an action on each retry with the current exception and retry count.

Policy
.Handle<ArgumentNullException>()
.Retry(3, (exception, count) =>
{
// do something
});

Retry forever :-
As the name suggests this would retry forever.

Policy.Handle<ArgumentNullException>().RetryForever();

Suppose you want to Retry forever, calling an action on each retry with the current exception.

Policy
.Handle<ArgumentNullException>()
.RetryForever(exception =>
{
// do something
});

Retry and Wait :-
If you want to Retry and wait for a specified duration between each retry.

Policy
.Handle<ArgumentNullException>()
.WaitAndRetry(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(3)
});

And if you want to Retry and wait for a specified duration between each retry, calling an action on each retry with the current exception and duration

Policy
.Handle<ArgumentNullException>()
.WaitAndRetry(new[]
{
1.Seconds(),
2.Seconds(),
3.Seconds()
}, (exception, timeSpan) => {
// do something
});

Circuit Breaker :-
If you want to break the circuit after the specified number of exceptions and keep circuit broken for the specified duration.

Policy
.Handle<ArgumentNullException>()
.CircuitBreaker(2, TimeSpan.FromMinutes(1));

Once you have set up a policy, you execute on it.


Policy
  .Handle<SqlException>(ex => ex.Number == 1205)
  .Or<ArgumentException>(ex => ex.ParamName == "example")
  .Retry()
  .Execute(() => DoSomething());

Asynchronous Support (.NET 4.5 Only) :-

You can use Polly with asynchronous functions by using the asynchronous methods

  • RetryAsync
  • RetryForeverAsync
  • WaitAndRetryAsync
  • CircuitBreakerAsync
  • ExecuteAsync

In place of their synchronous counterparts

  • Retry
  • RetryForever
  • WaitAndRetry
  • CircuitBreaker
  • Execute

For example :-


await Policy
.Handle<SqlException>(ex => ex.Number == 1205)
.Or<ArgumentException>(ex => ex.ParamName == example)
.RetryAsync()
.ExecuteAsync(() => DoSomethingAsync());


I hope it will be useful and let me know if you want improvement because this is my first blog and by this blog I have started my journey of blogging!

Happy coding!

Advertisements

3 thoughts on “Polly : A latest nuget package for Exception handling

  1. Neel, have you tried using Polly with ASP.NET Core at all? I wasn’t too sure if your post was in the context of ASP.NET “classic” or ASP.NET Core. I’m not too sure if Polly supports ASP.NET Core yet.

    Thanks!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s