General handling of AJAX call error on client side

2019-05-14 15:28发布

We have a JSF 2.2 application using PrimeFaces.

Now, when an error occurs, I check for an AJAX request and deliver a partial response (as shown in BalusC's anwer to this question).

But what is, if there's no server anymore to handle the error, e.g. due to connection loss? At the moment, just nothing happens, leaving the user puzzled.

I found a hint in that question, which works, but I'd like to solve this in a general way, so that all AJAX calls which fail try to redirect to the start page - and then may receive the browser connection error message.

1条回答
聊天终结者
2楼-- · 2019-05-14 15:53

For standard JSF ajax, use jsf.ajax.addOnError() to set the default error handler. E.g.

jsf.ajax.addOnError(function(data) {
    alert(data.responseText);
});

See also chapter 13.3.6.2 of the JSF 2.2 spec. You can find all properties of data object in table 14-4 of the JSF spec.

For PrimeFaces 4+, hook pfAjaxError event in jQuery (before 4, just use ajaxError). E.g.

$(document).on("pfAjaxError", function(event, xhr, options) {
    alert(xhr.responseText);
});

Just customize it accordingly to show some div in top.

查看更多
登录 后发表回答