UPD I've updated code for Aspects to throw exception further
I have SpringBoot application, service class and I need to implement Exception Handler for my service (not MVC). The task is to log error and throw it further to the client.
I decided to use Aspect with @AfterThrowing
advice. I'm gonna catch few exceptions (that extend RuntimeException
) at AspectOne
aspect. And for other cases I need to catch exceptions (that extend RuntimeException) at AspectTwo
aspect.
So I did the following code:
public class MyOwnException extends RuntimeException {
}
@Aspect
@Order(0)
@Component
public class AspectOne {
@Pointcut("execution(* com.test.MyService.*(..))")
public void logException() {}
@AfterThrowing(pointcut="logException()", throwing="ex")
public void logException(MyOwnException ex) {
System.out.println("MyOwnException has been thrown: " + ex.getMessage());
throw ex;
}
}
@Aspect
@Order(1)
@Component
public class AspectTwo {
@Pointcut("execution(* com.test.MyService.*(..))")
public void logException() {}
@AfterThrowing(pointcut="logException()", throwing="ex")
public void logException(RuntimeException ex) {
System.out.println("Some unknown exception has been thrown: " + ex);
throw ex;
}
}
The problem is that AspectTwo
is executed in both cases for MyOwnException
and other ancestors of RuntimeException
. How can I limit AspectTwo
to be executed only when AspectOne
haven't caught the exception?
Seems like @Order
annotation works not as I expected.
How about a little hack to indicate an exception is already handled/adviced ?
Also note that , the order of execution to be
AspectOne
beforeAspectTwo
here , theOrder
should be specified as 1 forAspectOne
and 0 forAspectTwo
.From the reference documentation section : Advice Ordering
Following code leverages the Throwable.addSuppressed() method to indicate an exception object is already handled/adviced.
--
Add an
Exception
class to be used as an indicator.AspectOne
with modifiedOrder
and logic to add a suppressed exception.AspectTwo
with modifiedOrder
and logic to check for already adviced.