题
我对如何在Struts2中进行错误处理感到困惑。我希望制作一次中央页面,如果发生错误,用户将被定向。此外,当发生错误时我想记录它,因为我使用的是log4j,我将它记录为 log.error(e.getMessage(),e);
但是,在我的动作类中,如果我发现错误(将我的所有代码都放在try / catch中),那么中央/常见错误页面就不会出现。所以我决定不捕获错误,如果我没有发现错误,那么中央错误页面就出现了。但是现在如何将错误消息/ stacktrack放入日志?
阅读此链接后 我做了以下事情:
<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>
根据上面的配置,最初在reports.ReportSelection中引发错误(但我没有在那里捕获)所以最后控件来到com.myErrorClass。我可以在这个类中记录错误,但我的问题是,日志消息是否仍然可用...因为它最初是在reports.ReportSelection中抛出的?
解决方案
在你捕获并记录它之后,你正在回顾它吗?如果你这样做,那么框架异常管理应该启动。你的错误处理代码应该类似于:
catch (Exception e) {
log.error(e.getMessage(), e);
throw e;
}
有了这个,你应该能够回到简化的日志记录方法,并在动作类中重新显示它,并配置一个全局错误页面。
其他提示
以下是记录操作引发的错误的方法。我不知道为什么默认情况下没有打开它。把它放在你的struts.xml文件中。
<interceptors>
<interceptor-stack name="errorloggingStack">
<interceptor-ref name="defaultStack">
<param name="exception.logEnabled">true</param>
<param name="exception.logLevel">ERROR</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="errorloggingStack"/>
您不需要在每个操作方法周围都有try-catch块。
作为替代方案,您也可以“覆盖” defaultStack拦截器堆栈
<interceptors>
<interceptor-stack name="defaultStack">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="exception">
<param name="logEnabled">true</param>
<param name="logLevel">WARN</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
不隶属于 StackOverflow