LOL at my own post title. Pardon me.
Michael Wolfenden has a very clever open source library 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.
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!
Polly has a fluent interface to make expressing rules like that much easier. For example:
// Single exception type
Policy
.Handle()
// Single exception type with condition
Policy
.Handle(ex => ex.Number == 1205)
// Multiple exception types
Policy
.Handle()
.Or()
// Multiple exception types with condition
Policy
.Handle(ex => ex.Number == 1205)
.Or(ex => x.ParamName == "example")
Then you can add Retry() logic, which is fantastic.
// Retry multiple times, calling an action on each retry
// with the current exception and retry count
Policy
.Handle()
.Retry(3, (exception, retryCount) =>
{
// do something
});
Even do retries with multiplicative back off!
// Retry a specified number of times, using a function to
// calculate the duration to wait between retries based on
// the current retry attempt, calling an action on each retry
// with the current exception, duration and context provided
// to Execute()
Policy
.Handle()
.WaitAndRetry(
5,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
(exception, timeSpan, context) => {
// do something
}
);
Once you have set up a policy, you execute on it.
Policy
.Handle(ex => ex.Number == 1205)
.Or(ex => ex.ParamName == "example")
.Retry()
.Execute(() => DoSomething());
Polly also supports the more sophisticated "Circuit Breaker" policy. For more information on the Circuit Breaker pattern see:
Circuit breaker tries and then "Trips the circuit breaker" so you'll get a BrokenCircuitException for some amount of time. This is a great way to give an external system to chill for a minute if it's down. It also externalizes the concept so that you could theoretically handle a down database the same as you handle a down external web API.
// Break the circuit after the specified number of exceptions
// and keep circuit broken for the specified duration
Policy
.Handle()
.CircuitBreaker(2, TimeSpan.FromMinutes(1))
You can explore the code, of course, up on Github in the Polly repository. Go give the Polly project a star. They've recently added async support for .NET 4.5 as well!
Sponsor: Welcome this week's feed sponsor, Stackify! - The only developer-friendly solution that fully integrates .NET error & log management with application monitoring. Easily isolate issues and focus your efforts – Support less, Code more. Free trial
© 2014 Scott Hanselman. All rights reserved.