Search code examples
javastruts2struts2-json-plugin

Json Plugin and Global exception in Struts


I am trying to return a JSON formatted global exception. This is my current struts.xml. I am not sure what is it that I am missing.

<struts>

<constant name="struts.devMode" value="true" />
<constant name="struts.custom.i18n.resources" value="global" />
<constant name="struts.configuration.xml.reload" value="true" />

<package name="mkaStrive" extends="json-default">
    <interceptors>
        <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor" />
        <interceptor-stack name="mobileStack">
            <interceptor-ref name="json" />
            <interceptor-ref name="defaultStack" />
        </interceptor-stack>
    </interceptors>
    <default-interceptor-ref name="test" />

    <global-results>

        <!-- Exceptions are handled by ExceptionAction -->
        <result name="exception" type="chain">
            <param name="actionName">exception</param>
        </result>

    </global-results>

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

    <action name="exception" class="n.a.exception.ExceptionAction" />

    <action name="getQuestionsList" class="n.a.mkastrive.action.GetQuestions" method="execute">
        <interceptor-ref name="json" />
        <result type="json"></result>
    </action>       
</package>

My GetQuestions action for now simply throws exception:

public String execute() throws Exception {
    throw new Exception("TEST");
}

From here ideally it should see that I have global-results and then chain to the action named exception.


Solution

  • The only issue I see in the struts.xml you provide is the below :(typo ?)

    Use

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

    Instead of

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

    With this, you could verify that the control comes inside the execute method of exception action class : n.a.exception.ExceptionAction.

    Now, if you were to return a response that customises the thrown exception, you can include a json result as so:

    <action name="exception" class="n.a.exception.ExceptionAction" >
      <result type="json"></result>
    </action>
    

    And for getting the Exception instance that was thrown from GetQuestions.execute(), you can use below in the exception action's execute method:

    (Exception)ActionContext.getContext().getValueStack().findValue("exception");

    You can operate on this and set required private fields in the class, so that they are available via public getters for json rendering. Just linking to a tutorial for json response.