Skip to Main Content
Spring: A Developer's Notebook
book

Spring: A Developer's Notebook

by Bruce Tate, Justin Gehtland
April 2005
Intermediate to advanced content levelIntermediate to advanced
216 pages
4h 44m
English
O'Reilly Media, Inc.
Content preview from Spring: A Developer's Notebook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaBeans Unleashed

JavaBeans Unleashed

Dr. Donald Doherty, Rick Leinecker
Beginning Spring

Beginning Spring

Mert Caliskan, Kenan Sevindik, Rod Johnson, Jürgen Höller
Hibernate Search in Action

Hibernate Search in Action

Emmanuel Bernard, John Griffin

Publisher Resources

ISBN: 0596009100Supplemental ContentErrata Page