Sunday, March 20, 2011

Exception handling with AOP

The throws advice is executed when a method throws an exception.

Handling exception by this method saves us from writing repeating try-catch block again and again.

Consider the following java code:

//interface with method throwing exception
public interface BusinessInterface {

public void someBusinessMethod() throws BusinessException;

//class implementing it
import org.springframework.jdbc.BadSqlGrammarException;

public class BusinessComponent implements BusinessInterface {

public void someBusinessMethod() throws BusinessException {
//we are raising a different exception to see the aspect coming into action
//assume that you are connecting to the database and something goes wrong
throw new BadSqlGrammarException("","",null);

So now this business logic may throw exception, and it will be handled by Aspect.

So we have to write handler for this:

import java.util.Locale;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;

public class ExceptionHandler implements MessageSourceAware {

private MessageSource messageSource;

public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;

@AfterThrowing(pointcut="execution(* someBusinessMethod(..))", throwing="ex")
public void handleException(JoinPoint jp, RuntimeException ex) throws Throwable {
System.out.println("Routine exception handling code here.");
System.out.println("Let's see who has raised an exception!");
throw new BusinessException(messageSource.getMessage(jp.getSignature().getName(), null, Locale.getDefault()));

Now if we want pre and post analysis of method, @Around advice will be handy for this.

Corresponding config file:

<aop:aspectj-autoproxy />

<bean id="messageSource" class="">
<property name="basename" value="ex6/messages" />

<bean id="exceptionHandler" class="com.xxxx.ExceptionHandler" />

<bean id="businessComponent" class="com.xxxx.BusinessComponent" />

No comments:

Post a Comment