【问题标题】:Usage of onError attribute in Richfaces 4.5Richfaces 4.5 中 onError 属性的使用
【发布时间】:2016-07-07 11:36:27
【问题描述】:

我想利用 Richfaces 中的 onerror 属性来处理我的 ajax 请求的异常。为此我使用了

<a4j:commandButton value="OK" 
actionListener="#{aBean.handler()}"
onerror="showNotification();">

在我的托管 bean 中:

ABean{
    public void handler(){
        throw new SomeException("Error to the browser");
    }
}

虽然,我在处理程序中抛出了异常,但我的 showNotification() 从未被调用。

我可以使用 onerror 属性处理我的应用程序级异常吗?非常感谢有关此主题的任何指示或示例。

【问题讨论】:

  • 你的意思是actionListener="#{aBean.handler}" 没有()
  • 我看不出#{aBean.handler()} 或#{aBean.handler} 两种方式有什么不同。不是吗?
  • 是的,这种情况下是的,但也请看我的答案。

标签: richfaces ajax4jsf onerror


【解决方案1】:

docs 中,您可以看到onerror 属性有效:

当请求导致错误时

这基本上意味着请求必须以 HTTP 错误结束。例如 HTTP 500,这可能意味着该服务器目前不可用。

例子(java):

public void handler2() throws IOException {
    FacesContext context = FacesContext.getCurrentInstance();
    context.getExternalContext().responseSendError(HttpServletResponse.SC_NOT_FOUND,
            "404 Page not found!");
    context.responseComplete();
}

a4j:commandButton (xhtml)

<a4j:commandButton value="OK" actionListener="#{bean.handler2}" 
    onerror="console.log('HTTP error');" />

在 JavaScript 控制台中,您应该会看到“HTTP 错误”。

在任何其他异常情况下,oncomplete 代码将被触发,因为 AJAX 请求以成功结束。因此,如果您不想对代码中的异常做出反应,则必须自己处理。有很多方法可以做到这一点。我用这个:

public boolean isNoErrorsOccured() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    return ((facesContext.getMaximumSeverity() == null) || 
                (facesContext.getMaximumSeverity()
                    .compareTo(FacesMessage.SEVERITY_INFO) <= 0));
}

而我的oncomplete 看起来像这样:

<a4j:commandButton value="OK" execute="@this" actionListener="#{bean.handler1}"
    oncomplete="if (#{facesHelper.noErrorsOccured})
        { console.log('success'); } else { console.log('success and error') }" />

和这样的处理程序:

public void handler1() {
    throw new RuntimeException("Error to the browser");
}

在 JavaScript 控制台中,您会看到“成功和错误”。


顺便说一句。最好写actionListener="#{bean.handler3}" 而不是actionListener="#{bean.handler3()}"。背后的原因:

public void handler3() { // will work
    throw new RuntimeException("Error to the browser");
}

// the "real" actionListener with ActionEvent won't work and
// method not found exception will be thrown
public void handler3(ActionEvent e) { 
    throw new RuntimeException("Error to the browser");
}

【讨论】:

  • 谢谢埃米尔。我只想将异常详细信息消息/数据从处理程序方法发送到浏览器作为错误响应的一部分。这样我就可以在 onerror 属性中使用它,例如 console.log(exceptionDetails);我使用了 onerror="console(event.data)" 但我在控制台中看到未定义。
  • 很高兴我能帮上忙。但这是另一个问题。如果您喜欢我对您原始问题的回答,请接受。如果您有不同的问题,请在不同的主题中提问。 (如果你没有先设置,你不能像这样使用event.data。)
猜你喜欢
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 2019-07-23
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
相关资源
最近更新 更多