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 its throwing
attribute.
Spring config
<bean name="tc" class="foo.bar.ThrowingClass"/>
<bean name="logex" class="foo.bar.LogException"/>
<aop:config>
<aop:aspect id="afterThrowingExample" ref="logex">
<aop:after-throwing method="logIt" throwing="ex"
pointcut="execution(* foo.bar.*.foo(..))"/>
</aop:aspect>
</aop:config>
The throwing
attribute is the parameter name of the aspect's handler method (here it's LogException.logIt
) that gets called on the exception:
Aspect
public class LogException {
public void logIt(AnException ex) {
System.out.println("*** " + ex.getMessage());
}
}
The XML and method combo defines the exception type that the aspect applies to. In this example, ThrowingClass
throws AnException
and AnotherException
. Only AnException
will have the advice applied because of the advice's method signature.
See example project on github for full source.
Check out a AfterThrowingAdvice. An example is found here (search for "After throwing advice") and you'll find it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With