3

我有一个 web 应用程序(2.5 servlet 规范),带有一个 spring dispatcherservlet 处理 /error/* 上的任何内容,以及一个配置为将其路由到 /error/ 的错误页面,如下所示:

<servlet>
    <servlet-name>errorServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>errorServlet</servlet-name>
    <url-pattern>/erorr/*</url-pattern>
</servlet-mapping>
<error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/erorr/</location>
</error-page>

和 errorServlet-servelt.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
    <context:component-scan base-package="some.base.package"/>
    <bean id="simpleUrlController" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/*">errorController</prop>
            </props>
        </property>
    </bean>
    <bean id="errorController" class="ErrorController">
        <property name="formView" value="formView"/>
        <property name="commandClass" value="Error"/>
        <property name="commandName" value="errorNAMe"/>
    </bean>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

我需要帮助的地方:

  1. 这是否是解决错误的最佳方法。
  2. 我知道有一个 SimpleMappingExceptionResolver 我可以在我的配置中声明......但我在某处读到这个类很好,只有异常来自 spring 控制器而不是其他。
4

1 回答 1

5
  1. 我在我目前正在处理的应用程序中使用这种方法,它似乎工作正常。
  2. 这是真的,但没关系。如果它是一个 Web 应用程序,任何被抛出的异常最终都会冒泡到顶部,这应该是 Spring 控制器。然后它将根据您的配置从那里得到处理,无论是转发到另一个页面还是让您的应用程序爆炸。

这是一个很好的基础教程;如果你用谷歌搜索,还有其他的:http: //developingdeveloper.wordpress.com/2008/03/09/handling-exceptions-in-spring-mvc-part-2/

编辑:您不仅可以重定向到错误页面,还可以将这些异常放入数据库中,这样您就有了最常见的异常列表。Joel 和 Jeff 提到他们为 StackOverflow 执行此操作,并且该列表成为他们要修复的错误列表的一部分。

于 2009-07-27T16:19:19.123 回答