web xml中的自定义异常映射不起作用



我在JSF 2.2 webapp中有一个自定义的异常映射,如下所示。

    <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Project</display-name>
    <!-- Welcome page -->
    <welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <session-config>
       <!-- some codes-->
    </session-config>
    <error-page>
        <exception-type>se.telenor.ocfd.service.api.exception.CustomNotFoundException</exception-type>
        <location>/not_found.xhtml</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/404.xhtml</location>
    </error-page>
    <error-page>
        <location>/500.xhtml</location>
    </error-page>
    <error-page>
        <exception-type>javax.faces.application.ViewExpiredException</exception-type>
        <location>/session_timeout.xhtml</location>
    </error-page>
</web-app>

My Exception is

@ApplicationException
public class CustomNotFoundException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    public CustomNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }
    public CustomNotFoundException(String message) {
        super(message);
    }
}

但是当发生异常时,它是not redirect me to not_found.xhtml页,而不是always redirect to 500.xhtml页。

如果少了什么东西,谁来帮帮我好吗

如果异常被包装在另一个异常中,例如FacesExceptionELException,则可能发生这种情况,这取决于谁是第一个捕获实际异常并以包装形式将其进一步委托给调用者。这将只匹配<error-page>FacesExceptionELException中给定的<exception-type>

解决这个问题的一种方法是创建一个servlet过滤器,在doFilter()方法中做下面的事情:

try {
    chain.doFilter(request, response);
}
catch (ServletException e) {
    Throwable cause = e.getRootCause();
    if (cause instanceof FacesException || cause instanceof ELException) {
        throw new ServletException(cause.getCause()); // Unwrap and rethrow it.
    }
    else {
        throw e;
    }
}

通过/*的URL模式将其映射到FacesServlet或应用程序范围

如果您碰巧使用JSF实用程序库OmniFaces,则可以使用FacesExceptionFilter作为现成的解决方案。

最新更新