tags:

views:

825

answers:

1

I am a little confused on how to Error handling in Struts2. I wish to make once central page where the users will be directed if an error occurs. Furthermore, when an error occurs i wish to log it, since i am using log4j I'll be logging it as log.error(e.getMessage(), e);

However, in my action class if I catch the error (put all my code in try/catch) then the central/common error page does not come up. So I decided against catching the error, if i dont catch the error then central error page comes up. But now how do I put the error message/stacktrack into the logs??

After reading this link I did the following:

   <global-results>
                   <result name="Exception" type="chain">
                      <param name="actionName">ErrorPage</param>
                     <param name="namespace">/error</param>

                   </result>
            </global-results>

            <global-exception-mappings>
                <exception-mapping exception="java.lang.Exception" result="Exception"/>
            </global-exception-mappings>
            <action name="selectionPage" class="reports.ReportSelection">
                <result>/reports/SelectionPage.jsp</result>
            </action>

    </package>
    <package name="secure"  namespace="/error">
        <action name="ErrorPage" class="com.myErrorClass">
            <result>errorpage.jsp</result>
        </action>
    </package>

According to the above configuration, originally the error is thrown in reports.ReportSelection (but I am not catching it there) so finally the control comes to com.myErrorClass. I CAN log the errors in this class but my question is, whether the log message still be available...since it was originally thrown in reports.ReportSelection?

+1  A: 

After you catch and log it, are you retrhowing it? If you do, then the framework exception management should kick in. Your error handling code should look something like:

catch (Exception e) {
    log.error(e.getMessage(), e);
    throw e;
}

With that in place you should be able to go back to your simplified approach of logging and retrhowing it in the action class, and configuring a single global error page.

Brian Yarger