SeamFramework.orgCommunity Documentation

Chapter 4. Exception handling: Seam Catch integration

4.1. Background
4.2. Defining a exception handler for a web request

Seam Catch provides a simple, yet robust foundation for modules and/or applications to establish a customized exception handling process. Seam Servlet ties into the exception handling model by forwarding all unhandled Servlet exceptions to Catch so that they can be handled in a centralized, extensible and uniform manner.

The Servlet API is extremely weak when it comes to handling exceptions. You are limited to handling exceptions using the built-in, declarative controls provided in web.xml. Those controls give you two options:

To make matters more painful, you are required to configure these exception mappings in web.xml. It's really a dinosaur left over from the past. In general, the Servlet specification seems to be pretty non-chalant about exceptions, telling you to "handle them appropriately." But how?

That's where the Catch integration in Seam Servlet comes in. The Catch integration traps all unhandled exceptions (those that bubble outside of the Servlet and any filters) and forwards them on to Catch. Exception handlers are free to handle the exception anyway they like, either programmatically or via a declarative mechanism.

If a exception handler registered with Catch handles the exception, then the integration closes the response without raising any additional exceptions. If the exception is still unhandled after Catch finishes processing it, then the integration allows it to pass through to the normal Servlet exception handler.

You can define an exception handler for a web request using the normal syntax of a Catch exception handler. Let's catch any exception that bubbles to the top and respond with a 500 error.

@HandlesExceptions

public class ExceptionHandlers {
   void handleAll(@Handles CaughtException<Throwable> caught, HttpServletResponse response) {
      response.sendError(500, "You've been caught by Catch!"); 
   }
}

That's all there is to it! If you only want this handler to be used for exceptions raised by a web request (excluding web service requests like JAX-RS), then you can add the @WebRequest qualifier to the handler:

@HandlesExceptions

public class ExceptionHandlers {
   void handleAll(@Handles @WebRequest
         CaughtException<Throwable> caught, HttpServletResponse response) {
      response.sendError(500, "You've been caught by Catch!"); 
   }
}

Let's consider another example. When the custom AccountNotFound exception is thrown, we'll send a 404 response using this handler.

void handleAccountNotFound(@Handles @WebRequest

      CaughtException<AccountNotFound> caught, HttpServletResponse response) {
   response.sendError(404, "Account not found: " + caught.getException().getAccountId()); 
}

In a future release, Seam Servlet will include annotations that can be used to configure these responses declaratively.