Skip to content

AJAX Errors

Mark Reeves edited this page Jun 26, 2017 · 14 revisions

When an AJAX enabled UI component encounters an AJAX error it will attempt to display a message to the user.

Contents

Message in HTTP error response

This is the default behavior when an AJAX error is encountered. The message in the response body will be displayed to the user in place of the target UI widget.

HTTP/1.1 403 Forbidden
Date: Wed, 21 Oct 2015 04:29:00 GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 185
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html;

<!DOCTYPE html>
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /forbidden/foo.html
on this server.</p>
</body></html>

In the above example the user will see a message saying:

Forbidden

You don't have permission to access /forbidden/foo.html on this server.

Message Configured by Application

It is possible to override the default behavior by configuring the AJAX error handling module directly, like so:

require(["wc/config"], function(wcconfig){
  wcconfig.set({ messages: {
    404: "I can't find it!",
    error: "An error occurred and I have not set a specific message for it!"
  }
}, "wc/ui/xhr");});

Since 1.4.4 the configuration can contain either a string as shown above or a function that is passed a raw XHR and returns a string. This effectively allows the ability to handle ANY response format, be it XML, JSON, plain text, HTML, protobufs, binary data, anything.

Here is a possible example of handling JSON data:

/*
 Handles JSON response object with a "message" property,
 e.g. { "message": "An error occurred" }.
 Responds with the message and status code,
 e.g. might output "An error occurred 500"
 */
require(["wc/config"], function(wcconfig){
  wcconfig.set({ messages: {
    error: function(response) {
      var data;
      try {
        data = JSON.parse(response.responseText);
        data = data.message;
      } catch (ex) {
        data = response.responseText;
      }
      return data + " " + response.status;
    }
  }
}, "wc/ui/xhr");});

Fallback Error Message

If an error message is not set by any of the above methods WComponents will fall back to using the xhr_errormsg message from the wcomponents-i18n theme-messages.properties bundle.

In extreme and rare cases this will not be available (for example if the network cable is unplugged immediately after the page loads). In this contrived circumstance WComponents will fall back to a hardcoded, generic, English error message.

Clone this wiki locally