Error handling using aspect-oriented programming (AOP)

Code become’s messy with error handling logic all over our code, wouldn’t it be nice to be able to log the error, the offedning method name and the line number of the code that caused the error in the first place.

If you’ve done any MVC development then you are already familiar with AOP, [HandleError] is an example of an aspect and with very little effort indeed you can create your own. Creating an aspect means you can reuse logic for tracing, error handling and more very easily.

At work we use PostSharp for our AOP aspect-oriented programming and its doesn’t get much easier. The guys even give you an add on in visual studio and it walks you through how to go about learing AOP and how to create aspects using PostSharp – the tutorial is superb and very well thought out.

We have a class library logging class which we use as an aspect using Postsharp and this means that we can add a [Catch] attribute to the method and we now have error logging for this new method:-

[sourcecode language=”csharp”] [Catch] public MyNewMethod()
throw new applicationException();

And that is it, download the demo and give it a try its so easy but quite powerful – I recommend you take a look.