ajaxjsferror-handlingmojarra

What is the canonical way to handle errors during Ajax-requests?


For normal requests we can simple register an <error-page> in web.xml. However, this does not apply to Ajax-requests. By default errors during an Ajax-request will result in a little pop-window in the browser that shows the exception.

The main example I am struggling with is handling a ViewExpiredException in a uniform way. For standard requests, I redirect to a page that explains that the user is not logged in and provides a link to the login-page. I would like to do the same for Ajax-requests. There seem to be several ways:

  1. I could write a javascript function that handles the error on the client-side and redirects to the error-page. I would then have to add this function every <f:ajax>-tag on all pages using the onerror-attribute. Is there a way to tell JSF that I want to have this javascript-function as the default error-handler for all <f:ajax>-tags?
  2. I could use a custom exception-handler, as described in this blog. This seems to do what I want, but I wonder if it is overkill. Is there no simpler solution?

So my question is, how is this supposed to be solved? Which of the approaches I listed should be used? Is there another approach that I do not know of?


Solution

  • You can use faces.ajax.addOnError() to set the default error handler. E.g.

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

    See also chapter 13.3.6.2 of the Faces 4.0 spec. You can find all properties of data object in Table 16 Error Data Payload of the Faces 4.0 spec.

    If you happen to be still on JSF 2.x, then use jsf.ajax.addOnError() instead.