SeamFramework.orgCommunity Documentation

Chapter 24. Servlet Exception Handling Integration

24.1. Background
24.2. Defining a exception handler for a web request

Solder provides a simple, yet robust foundation for modules and/or applications to establish a customized exception handling process. Solder's Servlet integration ties into the exception handling model by forwarding all unhandled Servlet exceptions to the exception handling framework 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 exception handling integration in comes in. Solder's exception handling framework traps all unhandled exceptions (those that bubble outside of the Servlet and any filters) and forwards them on to Solder. Exception handlers are free to handle the exception anyway they like, either programmatically or via a declarative mechanism.

If a exception handler registered with Solder handles the exception, then the integration closes the response without raising any additional exceptions. If the exception is still unhandled after Solder 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 Solder 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 Solder!"); 
    }
}

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()); 
}