javablogspot

Just another WordPress.com weblog

Exception handling by Struts 2

Posted by damuchinni on February 13, 2009

Struts 2 has a neat feature where by it can automatically trap exceptions that you did not handle in your code. You can then decide what to do with this exception such as pass it off to your own custom action which can then write the exception to a database or send an email to someone. This is how it is done, in your struts.xml file you need to add:


<global-exception-mappings>
    <exception-mapping exception="java.lang.Exception" result="unhandledExceptionHandler"/>
</global-exception-mappings>

<global-results>
    <result name="unhandledExceptionHandler" type="chain">
        <param name="actionName">actionUnhandledExceptionHandler</param>
        <param name="namespace">/namespaceWhereActionIsDefined</param>
    </result>
</global-results>

<action name="actionUnhandledExceptionHandler" class="my.package.struts2.action.UnhandledExceptionHandler">
    <result name="canNotLogDatabaseError">/WEB-INF/page/error.jsp</result><!-- Used only if there is an error trying to log the exception -->
</action>

The above is pretty easy to follow once you know how it is done:
  1. The <global-exception-mappings> node has a child <exception-mapping …/>. The child will trap any type of exception (or you could be more specific and specify my.package.MyException) and then pass the result off to the action called unhandledExceptionHandler.
  2. The unhandledExceptionHandler is defined in the <global-results> section. This simply chains the action to another action, i.e. our custom action that will write the exception to the database, send an email or whatever else we tell it to do. In our case this will chain to /namespaceWhereActionIsDefined/actionUnhandledExceptionHandler
  3. In our package /namespaceWhereActionIsDefined we have our action definition which is just a normal Struts 2 action. As an example of such an action we may have the following (UnhandledExceptionHandler.java):
package my.package.struts2.action;

public class ActionUnhandledExceptionHandler extends BaseActionSupport {

    private Exception exception;

    @Override()
    public String execute() {

        if(exception != null){

            // Write exception to database, send an email or whatever you want to do here
            // ...
            // ...

            // Send the user to the error page with a message
            addActionError(getText("common.unknown.exception") + "<div class="errorMessageExceptionText">" + exception.toString() + "</div>");
            return ERROR; // Everything went OK, we just want to redirect to the error page"

        } else {
            logger.error("***** TRIED TO LOG EXCEPTION BUT EXCEPTION WAS NULL! I HAVE NOT LOGGED THIS EXCEPTION! *****");
        }

        addActionError(getText("actionUnhandledExceptionHandler.could.not.log.exception"));
        return "canNotLogDatabaseError";
    }

    /**
     * @param exception the exception to set
     */
    public void setException(Exception exception) {
        this.exception = exception;
    }
}


Struts will automatically inject the java.langException into the setter UnhandledExceptionHandler.setException()
making it immediately available to your action. Finally to show the


<s:if test="actionErrors != null && actionErrors.size > 0">
    <s:actionerror />
</s:if>


error message on your error page (/WEB-INF/page/error.jsp) just use:
About these ads

3 Responses to “Exception handling by Struts 2”

  1. David said

    Thanks for the nice example. However, when I tried running it, the exception in ActionUnhandledExceptionHandler is always null. Do you have any ideas about what I might have done wrong?

  2. Erik said

    This does not work. setException is never run…

  3. […] I was trying to follow this tutorial when writing this […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: