在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");
}