-->

Global Exception Handler in Struts 2

2019-08-03 22:23发布

问题:

I have a hybrid Struts 1 and Struts 2 application. My Struts 1 application has the following exception handler:

<global-exceptions>
    <exception type="java.lang.Exception" handler="myClass" />
</global-exceptions>

<global-forwards>
    <forward name="error" path="/error.jsp" module="/" />
</global-forwards>

I'm trying to accomplish a similar mapping in my Struts 2 part of the application. Here is what I have right now:

<global-results>
    <result name="myErrorHandler" type="redirectAction">
    <param name="actionName">myErrorAction</param>
    </result>
</global-results>

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

<action name="myErrorAction" class="myErrorAction">
      <result name="error">/error.jsp</result>
</action>

However, whenever I test out my error handler, I get an infinite loop (myErrorAction keeps calling itself). Is there a better way to setup a global exception handler in Struts 2? My action has custom code which creates special log entries and builds the error message to display to the user on the jsp page.

回答1:

Are you 100% sure that your myErrorAction (or your error.jsp) is not throwing an Exception? That would account for the infinite loop.

One should take much care that the resources that handle exceptions are totally sure in this regard.