I'm trying add some monitoring when some specific exception occurs. For example, if I have an aspect like this:
@Aspect
public class LogAspect {
@AfterThrowing(value = "execution(* *(..))", throwing = "e")
public void log(JoinPoint joinPoint, Throwable e){
System.out.println("Some logging stuff");
}
}
And test class:
public class Example {
public void divideByZeroWithCatch(){
try{
int a = 5/0;
}
catch (ArithmeticException e){
System.out.println("Can not divide by zero");
}
}
public void divideByZeroWithNoCatch(){
int b = 5/0;
}
public static void main (String [] args){
Example e = new Example();
System.out.println("***** Calling method with catch block *****");
e.divideByZeroWithCatch();
System.out.println("***** Calling method without catch block *****");
e.divideByZeroWithNoCatch();
}
}
As an output i will get:
***** Calling method with catch block *****
Can not divide by zero
***** Calling method without catch block *****
Some logging stuff
I was wondering if there is way for me to intercept method execution just after throwing exception, do something in my advice and continue with executing code in corresponding catch block?
So that if i call divideByZeroWithCatch()i can get:
Some logging stuff
Can not divide by zero
Yes, you can. You need a
handler()pointcut:Log output, assuming class
Exampleis in packagede.scrum_master.app:Update: If you want to know where the exception handler is located, there is a simple way: use the enclosing joinpoint's static part. You can also get information about parameter names and types etc. Just use code completion in order to see which methods are available.
Now update your code like this:
Then the console log says:
If that is good enough for you, then you are fine. But beware, the static part is not the full joinpoint, so you cannot access parameter values from there. In order to do that you have to do manual bookkeeping. And this is possibly expensive and can slow down your application. But for what it is worth, I show you how to do it:
Why do we need a
ThreadLocalmember for the joinpoint bookkeeping? Well, because obviously we would get into problems in multi-threaded applications otherwise.Now the console log says: