SYSK 226: Exception Handling in JavaScript

Have you seen a coding guidelines document that did not call for some sort of exception handling, be it in the form of __try/__except, On Error GoTo, try/catch, or any other way? Most developers would agree that it’s important to catch exceptions and, if not handle them, at least log the error details for later analysis and, perhaps, let the end user know that a problem has occurred via an application controlled popup dialog.

 

Sadly, this does not appear to be the case in client side scripting. It’s a rare case when I see try/catch constructs implemented in client-side JavaScript code. Perhaps it’s because sending error info to the server has been challenging in the past, or may be it’s because some developers are just not aware that JavaScript does have exception handling support…

 

The exception handling syntax in JavaScript is simple:

try

{

// Your code goes here

}

catch(e)

{

// Logging goes here

// The exception object e has the following properties:

// name, number, description, message and propStackFrame

}

 

So, next time you write some JavaScript code, consider utilizing XMLHttpRequest object to asynchronously call a web service and report a client-side error… It’s could be done with just a few lines of code. And with .NET 3.0 coming out shortly, it’ll be easier than ever to do same.

 

Tip: while still in development, add

debugger;  

statement as the first line in the catch block, and you’ll be able to suspend the execution of the application, evaluate object values, execute instructions one line at a time, etc.