Thursday, October 4, 2012

Error.stack: a JavaScript stacktrace

By default, JavaScript error handling will not give you much (extra) information. One way to get some extra info is by using the Error.stack property. Error.stack, while not a published ECMAScript 5 standard, is broadly supported on the web, and enables the developer to readily drill down into errors. This can quickly show you where the problem originated, and will help you to walk the call tree back to where the error condition began. This can be especially useful if you send the client side errors back to the server to store them somewhere and want to debug the problem later.
Imagine you try to execute the following code(which will fail because d does not exist):
function a() {
 return d;
}

function b() {
 return a() * 5;
}

function c() {
 return b() * a() * b();
}

c();

If you wrap this in a try-catch block and write-out the stack trace, you’ll get the following info:
a@http://localhost/ErrorStackSample/:10
b@http://localhost/ErrorStackSample/:14
c@http://localhost/ErrorStackSample/:18
@http://localhost/ErrorStackSample/:20

This will already get you a lot further when you try to find the root cause of an obscure Java Script error. Currently this property is supported on the following browsers: Chrome, Firefox, IE 10, Opera, Safari.

More information: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Error/Stack

1 comment:

jowdjbrown said...

It should work with any editor or tool that supports using external tools to process files. Codcow