|
Error Logging with AJAX A Quick Script to Extend Your Error Logging Capabilities to the Client Published Sun, Sep 30, 2007 at 6:21 PM If you've done any amount of server-side scripting (CF, PHP, RoR, .NET, etc.), you already know the benefits of error handling. It allows you to capture unusual, sometimes unforeseen, errors that can occur in your code and handle them gracefully so your users get proper feedback on what just happened. No matter how great a programmer you are, something out of your control will break your code. Its your responsibility to provide a safety net when this happens. Since most developers would generally agree with my sentiment, why don't you see AJAX applications properly handling client-side errors. The application that sticks out for me is Gmail. At least once a week I'll stumble upon a Javascript error and according to Firebug its not being logged. Why? Can't errors that bubble up to the application scope be captured? Yes. Be better than Google. Here's how: What's it doing? Well, first off this is a Prototype Class so you need to include prototype.js in order to use it. Here's the breakdown: 1. The window.onerror event is set to call ErrorLogger.onError. When an unhandled error bubbles up to the window scope, onError will be called to handle it. 2. Three arguments are passed into the onError function ( msg, URI, line ). 3. An Ajax request with some additional browser information is constructed and posted to the URL specified in the constructor. 4. Lastly, the onError function returns true so the browser knows to disregard the error. Can you just show the syntax for use? No problem. When you click on the button labeled "Throw Error", the ErrorLogger class will gracefully handle the error and post some useful debug information to your server. From there you can do whatever you want. Personally, I just toss it in a log file that I monitor. All that in less than 1KB, not bad. Also, note that you can provide a function to be executed when an error occurs so you can give your users a little feedback. See the example above. I've tested it on IE6/7, Safari 2/3, and FF 1.5/2. Let me know if you have a chance to give it a try on another browser. As always, I value your thoughts, comments, and criticisms. You can send them to tcullen@pierinc.com. Cheers, Todd |