I’m trying to configure Spring so that it executes advice when a specific exception subclass (MyTestException) is thrown:
public class MyTestExceptionInterceptor implements ThrowsAdvice {
public void afterThrowing(Method method, Object[] args, Object target, Exception exc) {
// I want this to get executed every time a MyTestException is thrown,
// regardless of the package/class/method that is throwing it.
}
}
And the XML config:
<bean name="interceptor" class="org.me.myproject.MyTestExceptionInterceptor"/>
<aop:config>
<aop:advisor advice-ref="interceptor" pointcut="execution(???)"/>
</aop:config>
I have a feeling that I should be using the target pointcut specifier (instead of execution) since – according to the Spring docs – it seems as though target allows me to specify the type of exception to match against, but I’m not sure if that’s wrong, or what my pointcut attribute needs to look like.
I would greatly prefer to keep the AOP config done in XML (as opposed to Java/annotations, but I could probably translate an annotation-based solution into XML if need be.
I’d use an
<aop:after-throwing>element and itsthrowingattribute.Spring config
The
throwingattribute is the parameter name of the aspect’s handler method (here it’sLogException.logIt) that gets called on the exception:Aspect
The XML and method combo defines the exception type that the aspect applies to. In this example,
ThrowingClassthrowsAnExceptionandAnotherException. OnlyAnExceptionwill have the advice applied because of the advice’s method signature.See example project on github for full source.