2014-09-06 89 views
1

使用Spring 2.5.6,我的SimpleMappingExceptionResolver正是如此配置的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错误。

回答

1

几个小时后,认为web.xml中可能存在错误/ module-illegal-arg.jsp或可能需要其他配置的错误,我跳入调试器并将其追溯到getDepth()方法在SimpleMappingExceptionResolver.java中。

基本上,它将Exception条目与MissingServletRequestParameterException相匹配。虽然Exception是超级类,但人们会认为这种方法更喜欢直接匹配几个级别的匹配。实际上,这是getDepth()的全部目的。上线366给出了最后的线索:

if (exceptionClass.getName().indexOf(exceptionMapping) != -1) { 

所以基本上,例外是任何类在名称中的工作匹配的异常,在深度为0级。

那么,为什么IllegalArgumentException异常并且MissingServletRequestParameterException没有?底层存储是一个HashTable。 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>