I have a WCF service which logs any exceptions and then throws them as FaultExceptions.
I am doing a lot of repetition e.g. in each service method.
try {
// do some work
}
catch(Exception ex)
{
Logger.log(ex);
// actually will be Fault Exception but you get the idea.
throw ex;
}
I am looking for a more elegant way to do this as I am cutting and pasting the try/catch throughout each service.
Is there a design pattern /C# trick that could be used to make this more elegant?
Design patterns are solutions to software design problems you find again and again in real-world application development. Patterns are about reusable designs and interactions of objects. The 23 Gang of Four (GoF) patterns are generally considered the foundation for all other patterns.
Yes, there are. Lazy initialization, singleton, object pool, object state etc.
You're talking about AOP - Aspect Oriented Programming
Here's how I do it by passing the "work" as a lambda:
public partial static class Aspect
{
public static T HandleFaultException<T>( Func<T> fn )
{
try
{
return fn();
}
catch( FaultException ex )
{
Logger.log(ex);
throw;
}
}
}
Then to use it:
return Aspect.HandleFaultException( () =>
{
// call WCF
}
);
There are other ways to achieve the same goal, and even some commercial products, but I find this way to be the most explicit and flexible.
For example, you can write an aspect that creates and disposes the client for you:
public partial static class Aspect
{
public static T CallClient<T>( Func<Client, T> fn )
{
using ( var client = ... create client ... )
{
return fn( client );
}
}
}
and so:
return Aspect.CallClient( client =>
{
return client.Method( ... );
}
);
And then, you can wrap all the aspects you normally want to apply and create one master aspect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With