Why the Exception raised from my Interceptor is no

2019-05-21 11:46发布

问题:

I have a custom Interceptor, from which I throw an Exception;

The Action(s) running that Interceptor is managed by Convention plugin;

The Exception raised by the Interceptor is globally defined in struts.xml for the package the Action is running into.

RESULT: the exception mapping is ignored and I get the

Struts Problem Report

Struts has detected an unhandled exception:

...

Stacktraces

java.lang.IllegalArgumentException: my message

I guess I'm just missing something stupid... we've already discussed of this in a similar question, but it's still not clear if it can or can't work this way:

struts.xml

<package name="my-package" namespace="my" extends="struts-default">
    <interceptors>

        <interceptor name="myInterceptor" class="foo.bar.MyInterceptor"/>

        <interceptor-stack name="myStack">
            <interceptor-ref name="myInterceptor"/>
            <interceptor-ref name="defaultStack"/>
        </interceptor-stack>

    </interceptors> 

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

    <global-results>
        <result name="input">/WEB-INF/content/my-input.jsp</result>
        <result name="error">/WEB-INF/content/my-error.jsp</result>
    </global-results>

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

Action

@ParentPackage("my-package")
@Namespace("/my/blabla/yadayada")
public class MyAction extends MyBaseAction {

}

Interceptor

@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
    // ....
    if (somethingWrong) {
        throw new IllegalArgumentException("All work and no play makes Jack a dull boy");
    }
}

I've also tried defining global result / global exception mapping in the abstract BaseAction, or in the physical real Action itself, but they're ignored too.

Any idea on what to add / remove / change in order to make it work as it should ? This is not esoteric stuff, this is basic :|

回答1:

The main candidate for exception mapping feature is actions throwing an exceptions.

Docs:

Exception mappings is a powerful feature for dealing with an Action class that throws an Exception. The core idea is that an Exception thrown during the Action method can be automatically caught and mapped to a predefined Result.

But exceptions thrown from interceptors can be also handled by exception interceptor. In order to catch other interceptors exceptions exception interceptor should be defined as the first interceptor in the stack.

From the ExceptionMappingInterceptor javadoc:

It is recommended that you make this interceptor the first interceptor on the stack, ensuring that it has full access to catch any exception, even those caused by other interceptors.