Writing a custom generic exception handler in Struts

No Gravatar

Exception handling in Struts is a very simple concept to grasp, once you know the tool that Struts has put in place to handle it. This tool is the org.apache.struts.action.ExceptionHandler . The ExceptionHandler mechanism allows you to configure it in the struts-config.xml file and then Struts will automagically pass any exception type it’s configured to handle to it at runtime. Here’s a simple example of how easy it is to create one of these classes .


package myapp.exc;

import org.apache.struts.action.ExceptionHandler;
//other struts imports

public class MyExceptionHandler extends ExceptionHandler {
  public ActionForward execute( Exception ex,
                              ExceptionConfig exConfig,
                              ActionMapping mapping,
                              ActionForm formInstance,
                              HttpServletRequest request,
                              HttpServletResponse response
  ) throws ServletException {
    //send email to support that something happened w/ stack trace included
    //print stack trace to logs
    ex.printStackTrace();
    return mapping.findForward("login");
  }
}

This method takes in several parameters (including the request/response objects) and returns the forward to where you want to take the user. After setting your class up, all you’ve got to do now is configure it in the struts-config.xml file. You add it to the global-exceptions section. Here’s an example of how to do that for 2 different handlers for 2 different types of exceptions.


<global-exceptions>
  <exception
    handler="myapp.exc.MyExceptionHandler"
    key="standard.error.message"
    path="/genericError.jsp"
    scope="request"
    type="myapp.exc.MyException"/>

  <exception
    handler="myapp.exc.AuthorizationExceptionHandler"
    key="unauthorized.error.message"
    path="/auth.jsp"
    scope="request"
    type="myapp.exc.AuthorizationException"/>
</global-exceptions>

As you can see, you can easily use what Struts has provided to setup a flexible declarative exception handling model for your application.

Hope this helps.

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *