Creating a Custom Exception Handler

 < Day Day Up > 



Strut's built-in exception handler will suit most exception-handling scenarios; however, your application may require a specialized exception handler. For this situation, Struts provides a simple interface for creating your own custom exception handler that can easily be plugged into the framework. Following are the two steps you need to take to create your own custom exception handler:

  1. Create a new exception-handler class.

  2. Add new exception-handler definitions to the struts-config.xml file.

The following sections walk through each step of the process in detail, illustrating how to create a custom exception handler that can send an e-mail when an exception is caught. The example is designed to be generic so that it can be used with any type of exception and can be easily enhanced.

Create a New Exception-Handler Class

The first step in creating a custom exception handler is to create an exception-handler class that can be plugged into Struts. Custom exception-handler classes must extend Struts' base org.apache.struts.action.ExceptionHandler class and override its execute( ) method. The execute( ) method of the ExceptionHandler class that gets overridden is very similar to the execute( ) method of the Action class and behaves almost identically. However, ExceptionHandler.execute( ) takes two additional arguments, java.lang.Exception and org.apache.struts.config.ExceptionConfig. Table 8-1 explains each of the ExceptionHandler.execute( ) method's arguments.

Table 8-1: The execute( ) Method Arguments

Argument

Description

java.lang.Exception

The exception that has been thrown and is to be handled.

org.apache.struts.config.ExceptionConfig

The ExceptionConfig object encapsulates the <exception> definition from the struts-config.xml file for this exception handler.

org.apache.struts.action.ActionMapping

The ActionMapping object encapsulates the <action> definition from the struts-config.xml file for the action that threw the exception that this exception handler is configured to handle.

org.apache.struts.action.ActionForm

The ActionForm object encapsulates the Form Bean associated with the action that threw the exception that this exception handler is configured to handle.

javax.servlet.http.HttpServletRequest

The HttpServletRequest object encapsulates the current HTTP request.

javax.servlet.http.HttpServletResponse

The HttpServletResponse object encapsulates the current HTTP response.

To illustrate how to create a custom exception handler, we'll examine a sample exception handler that can be used to send an e-mail with a stack trace for the exception when the handler is triggered. Following is the example EmailExceptionHandler class:

package com.jamesholmes.minihr.EmailExceptionHandler; import java.io.*; import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.struts.action.*; import org.apache.struts.config.*; public class EmailExceptionHandler extends ExceptionHandler {   private static final String EMAIL_SERVER = "smtp.company.com";   private static final String EMAIL_SENDER = "sender@company.com";   private static final String EMAIL_RECIPIENT = "receiver@company.com";   private static final String EMAIL_SUBJECT = "Exception Thrown";   public ActionForward execute(Exception ex,     ExceptionConfig config, ActionMapping mapping, ActionForm form,     HttpServletRequest request, HttpServletResponse response)       throws ServletException   {     // Send email with exception.     try {       sendEmail(ex);     } catch (Exception e) {       throw new ServletException(e);     }     // Forward processing to the default exception handler.     return       super.execute(ex, config, mapping, form, request, response);   }   private void sendEmail(Exception ex)     throws Exception   {     // Set the host SMTP address.     Properties props = new Properties();     props.put("mail.smtp.host", EMAIL_SERVER);     // Get the default mail session.     Session session = Session.getDefaultInstance(props, null);     // Store exception stack trace as message text string.     ByteArrayOutputStream stream = new ByteArrayOutputStream();     ex.printStackTrace(new PrintStream(stream));     String messageText = stream.toString();     // Create a message.     Message message = new MimeMessage(session);     message.setFrom(new InternetAddress(EMAIL_SENDER));     message.setRecipient(Message.RecipientType.TO,       new InternetAddress(EMAIL_RECIPIENT));     message.setSubject(EMAIL_SUBJECT);     message.setSentDate(new Date());     message.setText(messageText);     // Send the message.     Transport.send(message);   } } 

Instead of completely overriding the functionality of the base ExceptionHandler class, the EmailExceptionHandler class augments its functionality. The EmailExceptionHandler class takes the exception passed to it and uses JavaMail to send the exception's stack trace in an e-mail. After sending the e-mail, EmailExceptionHandler calls super.execute( ), which invokes the default exception handler. This example illustrates how you can jump into the exception-handling process and add processing of your own. Alternatively, you could create an exception handler that completely overrides the behavior of the base handler.

Add New Exception-Handler Definitions to the struts-config.xml File

After you have created the custom exception handler, you put it to use by adding exception-handler definitions to the struts-config.xml configuration file. Using a custom exception handler is not much different from using the default handler. All you have to add to the standard definition is the fully qualified class name of the handler with the exception tag's handler attribute, as shown next:

<exception type="com.jamesholmes.minihr.NoResultsFoundException"         handler="com.jamesholmes.minihr.EmailExceptionHandler"             key="error.NoResultsFoundException"            path="/exception.jsp"/>

Because the EmailExceptionHandler handler simply extends the base handler and does not completely override it, you must specify a path, by using the path attribute, for the handler to forward to. However, if you were to create a custom handler that completely overrides the base handler, you would not have to specify a value for the path attribute unless your handler wanted to use it. The type and key attributes are required regardless of what handler you use.



 < Day Day Up > 



Struts. The Complete Reference
Struts: The Complete Reference, 2nd Edition
ISBN: 0072263865
EAN: 2147483647
Year: 2003
Pages: 134
Authors: James Holmes

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net