【问题标题】:Linking Server Side Message/Exception with AJAX request使用 AJAX 请求链接服务器端消息/异常
【发布时间】:2012-05-28 18:49:36
【问题描述】:

我正在使用 Primefaces 进行 ajax 提交,但在将我的服务器端消息与我的 ajax 请求链接时遇到问题。 假设我有一个调用动作的按钮。 在我的托管 bean 中,我需要引发异常吗?如何将此消息传递到我的 ajax 请求中

public void checkout(ActionEvent event){
    if(expression){
        throw new CustomException("Account balance is not enough!");
    }
}

public class CustomException extends RuntimeException { 
    public CustomException(String message) {
        super(message);
    }
}

我该如何处理这种情况?我的 onerror javascript 方法能处理这个问题吗?

另外,在一种情况下,假设数据库已关闭,那么我该如何处理异常?我是否访问过错误消息 在我的 javascript 函数中?

public void checkout(ActionEvent event){
    try{
        //DB is down
        if(expression){
            throw new CustomException("Account balance is not enough!");
        }
    }catch(Exception e){

    }
}

【问题讨论】:

    标签: ajax jsf-2 exception-handling glassfish primefaces


    【解决方案1】:

    至于您的具体问题,您需要为此实现一个自定义 ExceptionHandler,它基本上在 ajax 请求中发生异常时执行以下操作:

    String errorPageLocation = "/WEB-INF/errorpages/500.xhtml";
    context.setViewRoot(context.getApplication().getViewHandler().createView(context, errorPageLocation));
    context.getPartialViewContext().setRenderAll(true);
    context.renderResponse();
    

    如果您想将web.xml 错误页面考虑在内,这并不完全是微不足道的。您需要解析整个web.xml 才能找到错误页面位置。 OmniFaces 实用程序库正好有这样一个异常处理程序,FullAjaxExceptionHandler。您可以找到完整的源代码here 和展示示例here

    至于您的具体功能要求,当只有用户错误时,我不会抛出异常。这是完全可以恢复的。您需要创建并添加一个FacesMessage 并使用ajax 来更新<h:messages><p:messages><p:growl>。 PrimeFaces 支持autoUpdate="true",它会根据ajax 请求自动更新。例如

    context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Insufficient balance", null));
    

    <p:messages autoUpdate="true" />
    

    仅在无法恢复的情况下(例如数据库关闭)才有意义。请注意,您通常不会自己抛出这样的异常。在 JPA 的情况下,它已经被作为 PersistenceException 抛出,而您又不应该在 JSF 托管 bean 中捕获它,而是放手。

    【讨论】:

    • 你为什么知道这么多东西?错误..开玩笑。一直感谢... :)
    猜你喜欢
    • 2019-06-01
    • 2018-01-13
    • 2021-10-28
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    相关资源
    最近更新 更多