Which Exceptions to declare/handle in struts xml

2019-02-20 17:43发布

问题:

There are Checked and Unchecked exceptions in Java.

I have one silly doubt regarding handling checked exception in mind as I am new to Struts2. We write try catch block to handle checked exceptions. So, we can write return statement in catch block and return view name of page which shows Exception/Error.

And what if I throw checked exception which is declared in struts.xml file and a result is a redirect to a Error/Exception page?

Does both are right ways for checked exception?

回答1:

The application level exceptions should be caught. If you throw an application level exception and didn't catch it, it could be caught by the exception interceptor if it's configured to the action. Note, the exception interceptor is on bottom of the defaultStack that allows to catch exceptions not only in the action but in the whole stack of interceptors. If you configured this interceptor to map exceptions it should handle and result returned after it, which also should be configured as global results, then your exception will be caught and result returned. If you didn't, the web container will handle the exception. The right way is to catch exception and return an error result, but if you can't do it then you should configure exception interceptor. Note, that struts container exceptions occurred in your code aren't handled by the exception interceptor. In this case you should catch the exception and set the state of the action to error and after that you can check that state first in the action execution to return an error result or throw an exception that could be caught by the exception interceptor in the code where you can't return an error result. More about exception configuration you can find in the documentation.



回答2:

The answer depends entirely on the application requirement in hand.

For e.g. I've coded an API, so for all exceptions the same page has to be returned. I have something like below in my code :

<global-results>
            <result name="errHandler" type="chain">
                <param name="actionName">errorProcessor</param>
                <param name="namespace">/</param>
            </result>
        </global-results>
        <global-exception-mappings>
            <exception-mapping exception="java.lang.Throwable" result="errHandler" />
        </global-exception-mappings>