使用Spring 2.5.6,我这样配置了SimpleMappingExceptionResolver
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="MismatchException">error/mismatch-error</prop>
<prop key="Exception">error/${module.render.error.logical.page}</prop>
<prop key="IllegalArgumentException">error/module-illegal-arg</prop>
<prop key="MissingServletRequestParameterException">error/module-illegal-arg</prop>
</props>
</property>
</bean>
这个想法是,对于 IllegalArgumentException 和 MissingServletRequestParameterException,我想要一个稍微不同的错误屏幕以及返回的 HTTP 状态代码 400。
IllegalArgumentException 工作得很好,引用的 JSP 正确地将状态设置为 400。MissingServletRequestParameterException 不起作用,而是收到一般的 500 错误。
最佳答案
几个小时后,我认为 error/module-illegal-arg.jsp 中可能存在错误,或者 web.xml 中可能需要其他配置,因此我跳入调试器并跟踪到 getDepth() 方法SimpleMappingExceptionResolver.java。
基本上,它将异常条目与 MissingServletRequestParameterException 相匹配。虽然 Exception 是父类(super class),但人们可能会认为该方法更喜欢直接匹配,而不是多层深度的匹配。事实上,这就是 getDepth() 的全部目的。第 366 行给出了最终线索:
if (exceptionClass.getName().indexOf(exceptionMapping) != -1) {
所以基本上,Exception 会在深度为 0 的情况下匹配名称中包含工作 Exception 的任何类。
那么为什么 IllegalArgumentException 起作用而 MissingServletRequestParameterException 不起作用呢?底层存储是哈希表。 IllegalArgumentException 哈希为早于 Exception 的值。异常哈希值早于 MissingServletRequestParameterException。
最终修复:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="MismatchException">error/mismatch-error</prop>
<!--
The full path is here in order to prevent matches on every class with the word
'Exception' in its class name. The resolver will go up the class hierarchy and will
still match all derived classes from Exception.
-->
<prop key="java.lang.Exception">error/${module.render.error.logical.page}</prop>
<prop key="IllegalArgumentException">error/module-illegal-arg</prop>
<prop key="MissingServletRequestParameterException">error/module-illegal-arg</prop>
</props>
</property>
</bean>
关于java - SimpleMappingExceptionResolver 仅适用于某些异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25695676/