简体   繁体   中英

Struts 2 Error Handling - How do I get the stackTrace and exception attribute?

I'm working with Struts2 and I'm having an issue with it's error handling mechanism. What I would like to do is to get the stackTrace and exception attributes in order to use it inside an action class (as for printing on the console) or inside a JSP page (without using taglibs).

Bellow there is a snippet of my struts.xml file:

<default-interceptor-ref name="defaultStack"/>

    <global-results>
        <result name="Exception" type="redirect">/error.action</result>
    </global-results>

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

    <action name="error" class="fend.ErrorAction">
        <result>/error.jsp</result>
        <interceptor-ref name="configStack"/>
    </action>

Thanks in advance!

in your JSP:

Exception : <s:property value="%{exception}" />

Exception stacktrace: <s:property value="exceptionStack"/>

I have the same set up as you except I redirect my exception to a JSP page exception.jsp.

In that page I have the following:

 <s:set name="ex" value="%{exception}" scope="page"/>

I know you want to avoid tag libs but perhaps the exception property will be available in your action? I remember having trouble passing the exception to my action as an Exception Object. I couuld only pass it as a string (my memory is fuzzy on this, its been a while)

In the end I redirected to a JSP page, included the above s:set tag and the following JSP sciptlet:

<%
Exception exMsg = (Exception)pageContext.getAttribute("ex");
logger.logException(application.getRealPath("")+ "/WEB-INF/error.txt",exMsg);
%>

<br/><br/>User friendly message here

The logger class got the stack trace from the Exception class and logs it to a file:

StackTraceElement[] stackTrace = exception.getStackTrace();

I remember having to get this done so it was one of those situations where I had to settle for some messy code but it worked... If you figure our something better let me know

You could use the com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor to log your exceptions at a desired log level (and a desired logger too). ( Read the documentation here )

The easiest way would be to customize the defaultStack in your struts.xml as below:

<interceptor-stack name="defaultStack">
  <interceptor-ref name="exception">
     <param name="logEnabled">true</param>
     <param name="logCategory">com.mycompany.app.unhandled</param>
     <param name="logLevel">WARN</param>
  </interceptor-ref>
  <interceptor-ref name="alias"/>
  <interceptor-ref name="servletConfig"/>
  ........
</interceptor-stack>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM