Spring AOP and Exception Intercepting

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:advisor advice-ref="interceptor" pointcut="execution(???)"/>

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:aspect id="afterThrowingExample" ref="logex">
    <aop:after-throwing method="logIt" throwing="ex"
                        pointcut="execution(* foo.bar.*.foo(..))"/>

The throwing attribute is the parameter name of the aspect's handler method (here it's LogException.logIt) that gets called on the exception:


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.

Need Your Help

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.