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

Pat*_*tan 1 jsf exception-handling custom-error-pages

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

    <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>
Run Code Online (Sandbox Code Playgroud)

我的例外是

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

如果缺少任何东西,有人可以帮助我。

Bal*_*usC 5

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

解决它的一种方法是创建一个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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