Saturday, 24 October 2015

Struts2 : Global exception mapping


In my previous post, I explained how to handle uncaught exceptions of action method. Suppose I had 5 action classes, all are retuning exceptions in some cases, I need to handle all these exceptions like following.
<action name="login1" class="strutstutorial.actions.LoginAction1">
  <exception-mapping result="error" exception="java.lang.Exception" />
  <result name="success">/success.jsp</result>
  <result name="error">/error.jsp</result>
</action>

<action name="login2" class="strutstutorial.actions.LoginAction2">
  <exception-mapping result="error" exception="java.lang.Exception" />
  <result name="success">/success.jsp</result>
  <result name="error">/error.jsp</result>
</action>

<action name="login3" class="strutstutorial.actions.LoginAction3">
  <exception-mapping result="error" exception="java.lang.Exception" />
  <result name="success">/success.jsp</result>
  <result name="error">/error.jsp</result>
</action>

<action name="login4" class="strutstutorial.actions.LoginAction4">
  <exception-mapping result="error" exception="java.lang.Exception" />
  <result name="success">/success.jsp</result>
  <result name="error">/error.jsp</result>
</action>

<action name="login5" class="strutstutorial.actions.LoginAction5">
  <exception-mapping result="error" exception="java.lang.Exception" />
  <result name="success">/success.jsp</result>
  <result name="error">/error.jsp</result>
</action>

Exception mapping is repeated in all action classes, don’t you think it is redundant. Yes it is, to solve this problem, structs come up with global-exception-mappings element, used to create global exceptions, applicable to entire project. When any action element don’t handle uncaught exception, it goes and check in global-exception-mappings element.

Any exception-mapping declared under the global-exception-mappings element must refer to a result in the global-results element.


For example,

<global-results>
  <result name="error">/error.jsp</result>
  <result name="sqlError">/sqlError.jsp</result>
</global-results>

<global-exception-mappings>
  <exception-mapping result="sqlError" exception="java.sql.SQLException" />
  <exception-mapping result="error" exception="java.lang.Exception" />
</global-exception-mappings>



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment