SafeExecute: A Functional Pattern for Cross-cutting Exception Handling
In some cases, you may find yourself implementing the exact same exception handling logic in several methods within a class, and your brain screams DRY! Here's way to use C# 3.0 to put that exception handling logic in one place:
public string Foo(string name, string greeting)
{
return SafeExecute<string>(() =>
{
return greeting + " " + name;
});
}
public int Bar(int i)
{
return SafeExecute<int>(() =>
{
return i + 1;
});
}
protected T SafeExecute<T>(Func<T> funcToExecute)
{
try
{
return funcToExecute.Invoke();
}
catch (Exception)
{
throw;
}
//if your error handling does not throw an exception
//return default(T);
}
The details of proper exception handling are elided above to allow the reader to focus on the functional aspects of the pattern. This pattern is really only useful when you are using exactly the same exception handling logic. This is often the case in classes due to common implications of SRP.
Actually, this pattern is more generalized by the common functional pattern of wrapping the execution of another function, but this provides a useful concrete example.