JSF ajax请求中的异常处理

Ran*_*ith 7 ajax jsf exception-handling jsf-2.2

在处理JSF ajax请求时抛出异常时,如何处理异常并访问堆栈跟踪?现在,当JSF项目阶段设置为Development时,我只在JavaScript警报中获取异常类名称和消息.更糟糕的是,当JSF项目阶段设置为Production时,没有任何视觉反馈,并且服务器日志不显示有关异常的任何信息.

如果这是相关的,我在Netbeans中使用GlassFish.

Bal*_*usC 16

这个问题在OmniFaces FullAjaxExceptionHandler展示中已知并充实.

基本上,你需要创建一个自定义ExceptionHandler标准JSF不提供一个开箱即用(至少,不是一个明智的).在那里你将能够获得Exception实例导致所有麻烦.

这是一个启动示例:

public class YourExceptionHandler extends ExceptionHandlerWrapper {

    private ExceptionHandler wrapped;

    public YourExceptionHandler(ExceptionHandler wrapped) {
        this.wrapped = wrapped;
    }

    @Override
    public void handle() throws FacesException {
        FacesContext facesContext = FacesContext.getCurrentInstance();

        for (Iterator<ExceptionQueuedEvent> iter = getUnhandledExceptionQueuedEvents().iterator(); iter.hasNext();) {
            Throwable exception = iter.next().getContext().getException(); // There it is!

            // Now do your thing with it. This example implementation merely prints the stack trace.
            exception.printStackTrace();

            // You could redirect to an error page (bad practice).
            // Or you could render a full error page (as OmniFaces does).
            // Or you could show a FATAL faces message.
            // Or you could trigger an oncomplete script.
            // etc..
        }

        getWrapped().handle();
    }

    @Override
    public ExceptionHandler getWrapped() {
        return wrapped;
    }

}
Run Code Online (Sandbox Code Playgroud)

要使其运行,请ExceptionHandlerFactory按如下方式创建自定义:

public class YourExceptionHandlerFactory extends ExceptionHandlerFactory {

    private ExceptionHandlerFactory parent;

    public YourExceptionHandlerFactory(ExceptionHandlerFactory parent) {
        this.parent = parent;
    }

    @Override
    public ExceptionHandler getExceptionHandler() {
        return new YourExceptionHandler(parent.getExceptionHandler());
    }

}
Run Code Online (Sandbox Code Playgroud)

需要注册的faces-config.xml内容如下:

<factory>
    <exception-handler-factory>com.example.YourExceptionHandlerFactory</exception-handler-factory>
</factory>
Run Code Online (Sandbox Code Playgroud)

也可以看看: