Struts 2 Exception Handling

Struts 2 is provided with good mechanism of handling exceptions in web applications. It is provide with logging the exception and redirecting the user to a customized page.

Exception Handling for a specific action: In struts.xml

<action name="hello" class="HelloAction" 
  <exception-mapping exception="java.lang.Exception"
       result="login" />
   <result name="login">/login.jsp</result>

If method throwEception of HelloAction will throw eception then user will be redirected to login.jsp

Global Exception Handling: In struts.xml

     <result name="error">/error.jsp</result>
 <exception-mapping exception="java.lang.Exception"
                            result="error" />

If Exception thrown from any method of any action then user will be redirected to error.jsp.

Logging Exceptions: Struts 2 is provided with ExceptionMappingInterceptor with which exceptions can be logged.

In struts.xml we need to specify some parameter to configure this:

  <interceptor-stack name="yourStack">
    <interceptor-ref name="defaultStack">
    <!--Enable logs -->
     <param name="exception.logEnabled">true</param>
     <!-- Specify log level error/debug/warn etc-->
     <param name="exception.logLevel">ERROR</param>
<default-interceptor-ref name="yourStack" />

Display Exception in the Output in a Jsp page:

Exception Name: <s:property value="exception" />
Exception Details: <s:property value="exceptionStack" />