我想利用Richfaces中的onerror属性来处理我的ajax请求的异常。为此,我使用了
<a4j:commandButton value="OK"
actionListener="#{aBean.handler()}"
onerror="showNotification();">
并在我的Managed bean中:
ABean{
public void handler(){
throw new SomeException("Error to the browser");
}
}
虽然,我已经在我的处理程序中抛出了异常,但我的showNotification()从未被调用过。
我可以使用onerror属性处理我的应用程序级异常吗?关于这个主题的任何指针或例子都非常感谢。
答案 0 :(得分:2)
在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");
}