Friday, September 09, 2005

XML.com: Errors and AJAX: "A Practical Example: Persisting Client-side Errors to your Server

Now that we have the basics of XMLHttpRequest and JavaScript error handling, let's look at an implementation that ties the two together. You'd think that JavaScript errors would be easy to spot given the prevalent 'Yellow Triangle of Death', but I still see them slip past the QA departments of several blue chip organizations' public-facing web sites.

Figure 1

So, here I will present a method for trapping errors and logging them back to the server in the hope that someone might be alerted to fix it. First, let's consider our client. The client should provide a class to be used as a singleton Logger object that can transparently handle the gritty details.

First we create the constructor:

// singleton class constructor
function Logger() {
// fields
this.req;

// methods
this.errorToXML = errorToXML;
this.log = log;
}

Next, we define the method that will serialize an Error object into XML. By default, an Error object only has two properties, name and message, but we will also check for a third called location which may be useful.

// map an error to an XML document
function errorToXML(err) {
var xml = '\n' +
'\n' +
'' + err.name + '\n' +
'' + err.message + '\n';
if (err.location) xml += '' + err.location +
'
';
xml += '
';
return xml;
}

Next is the log method. This is the meat and potatoes of the script that really brings together the principles described above. Notice that we are using the POST method for our call. What I am essentially creating here is a bespoke web service that is write-only and creates new records on each successful request. Therefore, POST is the only appropriate option.

// log method of Logger class
function log(err) {
// feature sniff
if (window.XMLHttpRequest) this.req = new XMLHttpRequest();
else if "

0 Comments:

Post a Comment

<< Home