如何处理JSF多个意外异常?

时间:2015-02-14 19:49:28

标签: jsf exception-handling

我正在实现一个ExceptionHandlerFactory来处理遵循JSF 2.0文档https://cwiki.apache.org/confluence/display/MYFACES/Handling+Server+Errors的应用程序中的意外错误。该实现适用于大多数情况。但是,当我关闭我的数据库时,发生了几个错误,初始化生成多个连接异常,如java.sql.SQLException,hibernate异常,bean注入异常等。方法handle()多次执行也重定向到错误页面多次。句柄代码如下:

public void handle() throws FacesException {

    final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
    while (i.hasNext()) {
        ExceptionQueuedEvent event = i.next();
        ExceptionQueuedEventContext context =
                (ExceptionQueuedEventContext) event.getSource();

        // get the exception from context
        Throwable t = context.getException();

        final FacesContext fc = FacesContext.getCurrentInstance();
        final Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
        final NavigationHandler nav = fc.getApplication().getNavigationHandler();

        //here you do what ever you want with exception
        try {

            //log error ?
            log.log(Level.SEVERE, "Critical Exception!", t);

            //redirect error page
            requestMap.put("exceptionMessage", t.getMessage());
            nav.handleNavigation(fc, null, "/error");
            fc.renderResponse();

            // remove the comment below if you want to report the error in a jsf error message
            //JsfUtil.addErrorMessage(t.getMessage());

        } finally {
            //remove it from queue
            i.remove();
        }
    }
    //parent hanle
    getWrapped().handle();
}

我在Firefox调试控制台中看到超过15个错误页面请求。 防止多重重定向的最佳方法是什么? 感谢。

1 个答案:

答案 0 :(得分:2)

每个请求确实只能发送1个响应。其中一种方法是将while替换为if,并删除其他while中的所有剩余例外情况。无论如何,第一个例外是最感兴趣的。所有其他例外仅仅是后果。

if (i.hasNext()) {
    // Original code here.
}

while (i.hasNext()) {
    i.next();
    i.remove();
}

您可以从JSF实用程序库inspirationFullAjaxExceptionHandler获取OmniFaces

另一种方法是收集某些列表中的所有异常,然后呈现一个错误页面,其中您相应地在某个迭代组件中显示该列表(例如ui:repeath:dataTable)。