Exception handling framework using Spring AOP
In this article I will look at the various features which are required for a good exception handling framework and how Aspect oriented programming (AOP) will be used in the design of an Exception handling framework.
Lets Look at the key feature of an Exception handling framework
- Propagating business and technical exceptions from the server side to the client side modules in a consistent manner.
- Returning error codes into human readable error messages.
- Handling checked and unchecked exceptions in a unified way.
- Throwing checked and unchecked exceptions and creating new instances initialized with an error code picked from a predefined set.
- Implementing new exception classes in a predefined inheritance hierarchy.
Learn more about exceptions here and find out the difference between Checked and unchecked exceptions here.
By large, Exceptions are classified in two categories
Application Exception are the recoverable exception of an application and these exception extend from java.lang.Exception class where as System Exceptions (Runtime exceptions) are irrecoverable exceptions and these exception extend java.lang.RuntimeException.
One of the most common requirement in exception handling is to log the exception which was thrown by the server side and in traditional approach, each exception handling (typically catch block) need to catch the specific exception and then log the exception to the logger. This is where AOP helps. Before looking at how AOP solves this problem, Lets look at what are the things that AOP offers to us to solve this problem.
Spring AOP provides a ‘AfterThrows’ advice interface in Spring 1.2 (Spring 2.0 supports @ThrowsAdvice annotation). Primary responsibility of the advice is that when ever a configured exception is thrown this advice will be invoked. Typically, each advice need to define a method which accepts a exception class as an argument. A typical signature looks like ‘public void afterThrowing(Exception exp)’, as the signature contains the exception class, it is possible to configure an advice to be active for any specific exception.
For a detail study on AOP Click here
Coming back to the problem of logging the catched exception, All that needs to be done is to configure an advice to catch a applicaiton and System exception; upon an exception, The advice gets invoked and the advice code logs the exception and throws the exception back to the client.
Written by Ravi Nallakukkala on November 29th, 2007 with
no comments.
Read more articles on Design.
- [+] Digg: Feature this article
- [+] Del.icio.us: Bookmark this article
- [+] Furl: Bookmark this article