JavaScript Quick Tip: Logging ClientSide Errors
As a developer you know how things work and always do the same actions, you say hey look error free. Get a user that has a happy click finger and watch your
application die right before your eyes. Wait it will not be before your eyes since you have no clue where this user is sitting using your application. Since
it is a clientside error will not even know that this is happening! One thing people seem to forget is that these wonderful clientside applications may be
full of errors and destroy your application. Bug free code is a dream, but with browser quirks and such, you can never test everything. So we probably need
to do something about this.
The easiest solution is to use the wonderful onerror event handler and get the error message to handle. The onerror event fires when a problem occurs. A lot
of people do not know this, but the onerror event does allow us to do more than keep browsers from freaking out. We can actually catch the Error Message, the
Line Number and the file the error fired in. Now this is a good starting point. So let’s build a simple code that allows us to log some errors.
All I am going to do is make a global array and stuff errors into it. Nothing too advanced for this example:
var arrErrors = new Array();
window.onerror = function ( strErr, strURL, strLineNumber ) {
strMess = "URL: " + strURL + "\nline number: " +
strLineNumber + "\nError Message: " + strErr;
arrErrors.push(strMess);
alert(arrErrors.join("\n__________\n\n"));
}
To see it in action click the following buttons to create errors, Button 1 calls a function with an error in it and button2 calls a function that does not exist.
Now I know what you may be saying, so what, I just alerted the errors, I still can not log them! Well this is where a simple error page comes into the mix. Instead of an alert message, redirect the user to the error page with the parameters in a query string. Or you can post the values obtained to a hidden iframe or even use a wonderful Ajax request to the server. The server side code on this error page that we are going to or posting too can add it to the server's error log. Now your error log will contain errors that you had no clue ever existed!
Hopefully this little tip can keep your application error free. Just remember that this onerror may cause some bad side effects to a page, especially if you forget to tell the user there was a problem. If you do it silently, they will click those buttons until their face turns red and leave since nothing would happen!
Also make sure to check out the JavaRanch journal a little later this month for an article I wrote on Ajax. It is great for anyone that is just starting to learn Ajax.
Eric Pascarello
Coauthor of Ajax In Action
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages