Random bits of information by a developer

31 January 2010

Seam In Depth: Exception Handling Part I

This three part entry will focus on the mechanisms Seam provides for handling exceptions gracefully -- both out of the box and extensible. An in depth look at where this happens in the Seam code base and user programmable extension points will be covered in Part I. Part II will dive even further and provide examples, and Part III will cover a custom ExceptionHandler implementation. Exception handling in any large application is something that's typically debated at least once: What does it mean, is it simply logging, what do we show the user, can our framework help etc. etc. All software developers will run into this debate at least once in their career, even if it's as simple as "what should I put in that catch block?" It's pretty safe to say swallowing exceptions (as a general rule of thumb) is a bad idea. Of course System.out.println(...) or log.error(...) really isn't much better. Typically the user should be informed that something they have done has resulted in an error on the server, and at the very least ask them to try again. We've all seen pages like the following: An error has occurred, please try again. If the error continues, please contact the webmaster / admin / whatever. This is a cop out and typically a sign of poor exception handling. At least the user didn't see that nasty stack trace or the 500 page from the server. If it's being left up to the user to make contact about an error, chances are it won't happen and the development team probably won't hear about it. Enter the debate about handling those exceptions, and being more pro-active about knowing about errors. Covering each of those questions is beyond the scope of this series, but the question about framework help certainly applies!

Built-in Handling

Seam proveds a simple, yet robust solution for integrating your exception handling strategy. Two methods exist out of the box for rudimentary handling: <exception> in pages.xml and annotations directly on application specific exceptions. Dan Allen covers these two options nicely in his book Seam in Action section 3.6, (if you don't already own a copy, go get one. It's a life saver) so these will only be briefly reviewed. A third option exists (and the before mentioned options, as well as the powerful Seam Debug page are all built on top of this mechanism) to allow complete customization of display to the end user and actions on the back-end: ExceptionHandler classes.

pages.xml

In a basic seam-gen application one will find the following stanzas of XML relating to exception handling:
    <exception class="org.jboss.seam.framework.EntityNotFoundException">
        <redirect view-id="/error.xhtml">
            <message severity="warn">Record not found</message>
        </redirect>
    </exception>
    
    <exception class="javax.persistence.EntityNotFoundException">
        <redirect view-id="/error.xhtml">
            <message severity="warn">Record not found</message>
        </redirect>
    </exception>
    
    <exception class="javax.persistence.EntityExistsException">
        <redirect view-id="/error.xhtml">
            <message severity="warn">Duplicate record</message>
        </redirect>
    </exception>
    
    <exception class="javax.persistence.OptimisticLockException">
        <end-conversation/>
        <redirect view-id="/error.xhtml">
            <message severity="warn">Another user changed the same data, please try again</message>
        </redirect>
    </exception>
    
    <exception class="org.jboss.seam.security.AuthorizationException">
        <redirect view-id="/error.xhtml">
            <message severity="error">You don't have permission to access this resource</message>
        </redirect>
    </exception>
    
    <exception class="org.jboss.seam.security.NotLoggedInException">
        <redirect view-id="/login.xhtml">
            <message severity="warn">#{messages['org.jboss.seam.NotLoggedIn']}</message>
        </redirect>
    </exception>
    
    <exception class="javax.faces.application.ViewExpiredException">
        <redirect view-id="/error.xhtml">
            <message severity="warn">Your session has timed out, please try again</message>
        </redirect>
    </exception>
    
    <exception class="org.jboss.seam.ConcurrentRequestTimeoutException" log-level="trace">
      <http-error error-code="503" />
    </exception>
     
    <exception>
        <redirect view-id="/error.xhtml">
            <message severity="error">Unexpected error, please try again</message>
        </redirect>
    </exception>
The format is pretty straight forward, a fully qualified class is given in the optional class attribute (leaving this out creates a catch-all handler) and the body is as follows from the XSD:
     <xs:element name="exception">
         <xs:annotation>
             <xs:documentation>A Seam exception handler</xs:documentation>
         </xs:annotation>
         <xs:complexType>
             <xs:sequence>
                 <xs:element minOccurs="0" ref="pages:end-conversation"/>
                 <xs:choice>
                     <xs:element ref="pages:http-error"/>
                     <xs:element ref="pages:redirect"/>
                 </xs:choice>
             </xs:sequence>
             <xs:attributeGroup ref="pages:attlist.exception"/>
         </xs:complexType>
     </xs:element>
     <xs:attributeGroup name="attlist.exception">
         <xs:attribute name="class" type="xs:token"/>
         <xs:attribute name="log" type="pages:tf-boolean"/>
         <xs:attribute name="log-level" type="pages:loglevel-values"/> 
     </xs:attributeGroup>
Redirects are the typical body of these XML blocks. FacesMessages can be added to the redirect as well as ending conversations. Typically these are used for exceptions the developer does not create, and therefore cannot be annotated; however, there may be uses for this style of handling with application exceptions. Please note that order does matter. If the catch-all handler is first, none of the other handlers will be used. Each of these entries creates an ExceptionHandler instance which is then added to the chain of handlers, which is covered later in the entry.

Annotations

Seam has three annotations to help with exception handling: @Redirect, @HttpError, and @ApplicationException. Only one of @Redirect or @HttpError may be used on an exception. Both allow for an info level FacesMessage to be added via the message attribute. The @Redirect annotation allows input for a view-id to which the user will be redirected. @HttpError simply returns the specified HTTP Error code. The last annotation, @ApplicationException provides the ability to rollback the transaction and end the existing conversation. These annotations are added directly on the Exception class that is created. Both of these built-in methods are built on top of two classes in Seam: org.jboss.seam.exception.Exceptions and org.jboss.seam.exception.ExceptionHandler. These two classes and their usage make up Seam's infrastructure for exception handling in an application, and provide customization to the developer.

Extensible Handling

The above two methods work well for simple cases. What if a team wants to be more pro-active about addressing errors? Could the application send the team emails about exceptions, or create bug tickets, or perhaps create a contextual log entry? This is where the exception handling capabilities of Seam really shine, and the answer to the above questions are all yes!

ExceptionHandler

package org.jboss.seam.exception;

import org.jboss.seam.faces.Navigator;

/**
 * An element of the chain that knows how to handle a 
 * specific exception type.
 * 
 * @author Gavin King
 *
 */
public abstract class ExceptionHandler extends Navigator
{  
   public enum LogLevel { fatal, error, warn, info, debug, trace }
   
   private boolean logEnabled;
   private LogLevel logLevel;
   
   public abstract void handle(Exception e) throws Exception;
   public abstract boolean isHandler(Exception e);
   
   public boolean isLogEnabled()
   {  
      return logEnabled;
   }
   
   public void setLogEnabled(boolean logEnabled)
   {  
      this.logEnabled = logEnabled;
   }
   
   public LogLevel getLogLevel()
   {
      return logLevel;
   }
      
   public void setLogLevel(LogLevel logLevel)
   {
      this.logLevel = logLevel;
   }   
   
}
The contract for this class is pretty straight forward. The only methods that need to be implemented are isHandler and handleException. Of course the isHandler implementation is trivial, and based on the needs of the handler the handleException implementation could be fairly simple as well. Take note that ExceptionHandler is a subclass of Navigator. There are methods defined in that class which may be helpful in some exception handlers.

Exceptions

This class is used in the org.jboss.seam.jsf.SeamPhaseListener before and after each phase of the JSF lifecycle and also in the org.jboss.seam.web.ExceptionFilter, wrapping the filter chain, and used again after any redirects that may happen after the filter chain has completed. As Dan Allen described it in Seam in Action: "A try-catch around the [whole request]" (Seam in Action pg. 126). There's only one method that needs any kind of attention: getHandlers. It returns a list that is used to add or remove ExceptionHandlers as needed. This method should be called in the @Create method, or constructor of any ExceptionHandler. ExceptionHandler classes should also be marked with @BypassInterceptors as there's no need to do bi-jection. A simple POJO, though, will typically suffice. Exception handling in Seam can be very powerful if used to it's full potential and should be an excellant tool in crafting an exception handler strategy for your application. The next entry in this series will demonstrate a custom exception handler in action.