Use of AOP in Cross Cutting Aspect of Error Handling

This post comes to us from Premier Developer consultant Crystal Tenn.

Cross Cutting Concerns are global concerns that span across methods, classes, applications—and can be concerns widely affecting a whole company or industry. Think of patient records or a financial history, and things always needed in those industries and how it affects each method of code! There are all kinds of required security for each step and any errors need to be carefully logged. In other words, integral parts of an application that have to be performed across the layers. Examples are Logging, Exception/Error Handling, Data Validation, Business Rules, Caching, Security, Communication, and others.

Aspect Oriented Programming (AOP) = program it once in its own section, and apply it as needed throughout the application. You should only add something to this section if it is to be reused often. If it is only a couple of times, try to implement it directly in your code to cut down on abstracting away too much. On the good, and bad, side... anything implemented here with a bug is easily fixed in one place, but can wreak havoc globally.

Java supports AOP, whereas C# only partially supports it (hence PostSharp and other 3rd party extensions). An application with strong architecture tends to have separate layers so different concerns don’t interact more than necessary, which is better for maintainability and for changes over time. AOP separates general code from code that is globally reusable code present throughout the layers; this is addressing the cross cutting concern.

So now our code, for example could be separated into:

  • Presentation layer
  • Domain logic layer
  • Data storage layer
  • General globally needed stuff layer (like Exceptions and Logging!)

You can standardize exception handling using AOP and reduce the amount of code written for exception handling. Most commonly in .NET, you will see post-processing (PostSharp) and code interception (dependency injection). As a sample for how to use AOP to address the cross cutting aspect of Error handling, we will talk about PostSharp.

Using PostSharp for post-processing, you can handle all of the exceptions in one system though a single function. Using PostSharp, you add an attribute [ExceptionAspect] to a method and PostSharp will wrap the method in a try/catch block for you. This cuts down on code added and allows you to easily reuse the same try/catch logic repeatedly. You can customize your exception handling logic with PostSharp. Please see here for detailed instructions on how to download and implement PostSharp:

Comments (0)

Skip to main content