Spring & JSF integration: Exception Handling

Most JSF developers will be familiar the “An Error Occurred” page that gets displayed when an unexpected exception is thrown somewhere their code. This page is really useful when developing but is not something you usually want for a production application. You generally have a couple of options when it comes to replacing this page with stock JSF; you can use define some HTML <error-page> elements in your web.xml or you can write a custom ExceptionHandler

Neither option is ideal for a Spring developer, <error-page> elements tend to be too simplistic and it is hard to use Spring concepts, such as dependency injection, with custom ExceptionHandlers. Luckily both JSF and Spring are very extensible frameworks so a project that I have been working on to integrate the technologies can offer some compelling alternatives.

The first option available allows ExceptionHandlers to be registered as Spring beans. Rather than use the existing javax.faces.context.ExceptionHandler class a new org.springframework.springfaces.exceptionhandler.ExceptionHandler interface is available. The interface is pretty straight forward, it defines a single handle method that should return true if the exception has been handled. The interface uses a generic to limit the types of exception considered.

public interface ExceptionHandler<E extends Throwable> {
  boolean handle(E exception, ExceptionQueuedEvent event) throws Exception;
}

All relevant beans beans that implement the ExceptionHandler interface will be consulted when an exception occurs from JSF. The first handler to return true will ‘win’ and subsequent handlers will not be called. You can use the org.springframework.core.Ordered interface or the @Ordered annotation if you need to sort your handlers. Of course, now that exception handlers are regular Spring beans, you can use all the standard Spring functionality such a dependency injection and AOP.

Now that we have basic exception handler hooks we can go on to offer a couple of useful implementations:

Sometimes the best way to handle certain exceptions is to simply show a message and remain on the current screen. For example, suppose a service throws TooManyResultsException when search queries are too broad. A simple message telling the user to ‘try again with more precise terms’ might be the only exception handling required. The org.springframework.springfaces.exceptionhandler.ObjectMessageExceptionHandler class builds on previous work that maps Objects to messages. Include an entry in your Spring MessageSource with the fully qualified name of the Exception as the key and a FacesMessage will be shown if the exception is thrown.

com.mycorp.search.TooManyResultsException=Too many results found, please try again with more precise search terms

You can easily map any number of exceptions to messages, you can even refer to properties of the exception using ‘{property}‘ placeholders in your message string. Messages can be displayed on the screen using standard JSF techniques (usually a <h:messages/> component).

Support for quickly mapping exceptions to messages is nice but it won’t be enough for a lot of applications and writing ExceptionHandler beans can quickly become tiresome. The final optional available is org.springframework.springfaces.mvc.exceptionhandler.DispatcherExceptionHandler. The DispatcherExceptionHandler provides a bridge between JSF and Spring MVC that allows you to use @ExceptionHandler annotations in your @Controllers as you would with any other Spring MVC application. Methods annotated with @ExceptionHandler are really versatile and can have very flexible signatures; you can deal with exceptions directly or return a view that should be rendered:

@ExceptionHandler
public String handle(ExampleException e) {
  return 'redirect:errorpage';
}

Using @ExceptionHandler annotations with Spring MVC is a very natural fit and there have been numerous articles written on the subject. Hopefully existing JSF developers will find the Spring MVC programming style an attractive alternative to standard JSF.

Please take a look at the other articles in this series and if you want to examine the exception handing code the ‘org.springframework.springfaces.exceptionhandler’ and ‘org.springframework.springfaces.mvc.exceptionhandler’ packages are a good place to start.

Reference: Integrating Spring & JavaServer Faces : Exception Handling from our JCG partner Phillip Webb at the Phil Webb’s Blog blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

3 Responses to "Spring & JSF integration: Exception Handling"

  1. Khaled Noordin says:

    Very good article but as usual Spring is really more understandable with an example or sample, it would have been really great if you could integrate you exeception handling with the current sample spring web flow reference project like the booking hotel application because right now this issue is not covered by the documentation and not integrate inside the reference sample.
    One more time thanks for this ticket

  2. JMS says:

    I can’t find any useful online reference to either org.springframework.springfaces.exceptionhandler.ObjectMessageExceptionHandler
    or simply ObjectMessageExceptionHandler.

    Does this really exist?

    I’m developing a Spring 3.1 MVC + JSF2 web app, and need a good, simple, reliable way to display something like FacesMessage. So far, I’ve found nothing like this in Spring. What a PITA.
    Thanks

Leave a Reply


six × = 42



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books