Enigma
Enigma

Reputation: 393

Can I keep @Around advice from interception exceptions in methods?

I want to use an advice in a java spring project to set some contexts before and after certain methods for database transactions, but if there's an exception I don't want the around advice to intercept this exception. However, I still need the finally/after part of the advice to execute to do some final things.

Should I switch to just using the @Before and @After advice, or is there a possible workaround with the @Around advice?

Upvotes: 0

Views: 30

Answers (1)

kriegaex
kriegaex

Reputation: 67387

You can, depending on your needs, either ignore the exception or log and re-throw it, whatever. Here are two possible variants to give you an idea:

package de.scrum_master.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class ErrorIgnoringAspect {
  @Around("execution(* org.acme..*(..))")
  public Object advice1(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println(">> " + joinPoint);
    try {
      return joinPoint.proceed();
    }
    finally {
      System.out.println("<< " + joinPoint);
    }
  }

  @Around("execution(* org.acme..*(..))")
  public Object advice2(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println(">> " + joinPoint);
    try {
      Object result = joinPoint.proceed();
      System.out.println("<< " + joinPoint + " -> result = " + result);
      return result;
    }
    catch (Throwable t) {
      System.out.println("<< " + joinPoint + " -> error = " + t);
      throw t;
    }
  }
}

If you just want to log the result or exception, and there is no need for exception handling, method parameter or result modification, of course you can also use a combination of @Before, @AfterThrowing (log exception) and @AfterReturning (log result), doing away with the need to use try-catch-finally or to proceed to the joinpoint.

Upvotes: 1

Related Questions