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:-

[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.

One thought on “Error handling using aspect-oriented programming (AOP)

  1. Hi there! This is my first comment here so I just wanted to give a quick
    shout out and say I truly enjoy reading your articles. Can you
    recommend any other blogs/websites/forums that deal with
    the same topics? Many thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s