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" 
                        method="throwException">
  <exception-mapping exception="java.lang.Exception"
       result="login" />
   <result>/hello.jsp</result>
   <result name="login">/login.jsp</result>
</action>

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

Global Exception Handling: In struts.xml

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

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:

<interceptors>
  <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>
    </interceptor-ref>
 </interceptor-stack>
</interceptors>
 
<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" />