Advising Exceptions

Often, you'll want to attach a service to exception logic, rather than mainstream code. It's especially important when exceptions force a major change in application flow, such as rolling back when an exception occurs, or automatically notifying administrators when some resource runs low.

Your application schedules bikes for a small store. You can use Spring's exceptions to generate a message whenever something goes wrong in the application. For simplicity, you'll send it to the console for now.

How do I do that?

The first job is to build an advisor. Use a simple class that implements the ThrowsAdvice interface, like in Example 6-10.

Example 6-10. ExceptionInterceptor.java

public class ExceptionInterceptor implements ThrowsAdvice {
    public void afterThrowing(Method m, Object[] args, 
           Object target, Exception ex) {

        System.out.println("Call to method " + m.getName( ) +
           " on class " + target.getClass( ).getName( ) + 
           " resulted in exception of type " + ex.getClass( ).getName( ));
        System.out.println("Exception message: " + ex.getMessage( ));
    }
}

Keep in mind that the ThrowsAdvice interface contains no method signatures; you can implement as many versions of afterThrowing as you want. Each must declare that last parameter as a subclass of Throwable. The other three parameters are optional.

Configure the parameters for the advice interceptor in the context. Next, you'll configure the advice (note that Example 6-11 goes back to using the ProxyFactoryBean from the first part ...

Get Spring: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.