I have several methods that look like this:
public void foo()
{
try
{
doSomething();
}
catch(Exception e)
{
Log.Error(e);
}
}
If you don't want to use an AOP approach, a method used at one of my previous employers for common exception handling across a set of class was to have a base class with a method similar to the following
protected TResult DoWrapped<TResult>(Func<TResult> action)
{
try
{
return action();
}
catch (Exception)
{
// Do something
throw;
}
}
With methods looking like.
public object AMethod(object param)
{
return DoWrapped(() =>
{
// Do stuff
object result = param;
return result;
});
}
Can't remember exactly, it's been a while. But similar to this.
Since you mentioned you're using WCF you can implement IErrorHandler interface and all exceptions would be routed to your method where you can log them.
You may try using: PostSharp
or try to google 'AOP' - 'Aspect Oriented Programming'. There are more similar techniques on the web.
You can use delegates and lambdas:
private void ExecuteWithLogging(Action action) {
try {
action();
} catch (Exception e) {
Log.Error(e);
}
}
public void fooSimple() {
ExecuteWithLogging(doSomething);
}
public void fooParameter(int myParameter) {
ExecuteWithLogging(() => doSomethingElse(myParameter));
}
public void fooComplex(int myParameter) {
ExecuteWithLogging(() => {
doSomething();
doSomethingElse(myParameter);
});
}
In fact, you could rename ExecuteWithLogging
to something like ExecuteWebserviceMethod
and add other commonly used stuff, such as checking credentials, opening and closing a database connection, etc.