Sunday, October 5, 2008

Exceptions in JavaScript

I did some intensive research into the topic of JavaScript exceptions yesterday. My main concern was, that while it is possible to throw basically every kind of object (Strings, numbers, booleans, Objects) via the throw operator, only the JavaScript standard exceptions will show up with a stack trace in firebug and only those will be clickable to jump to the source which caused the exception.

My research showed that it is indeed not possible to get firebug to show stack traces for custom exceptions. The main reason being really simple: The firebug console is a reflection of the standard error console and thus it cannot show more than is being shown by the standard error console.
There does not seem to be an easy way around it from the firebug point of view. I still hope that firefox will eventually add core support to enable a better experience in the firebug error console, but wel'll have to wait for that.

Among the things that I tried where to copy a core-JS error and manipulate the stack trace, etc. But all of those things won't trick the browser into thinking it has a real core exception.

Here are some basic advises when dealing with exceptions in JS
  • Never throw an exception in an asynchronous callback!!! Nobody will be able to catch it (without maybe playing ungly games with a global exception handler in window.onerror).
  • Use onError callback arguments instead.
  • I would not recommend to use custom exception classes in JS right now (but I would be very interested in a good best practive article on this topic, and I will do more research in this area)
I have an idea on how to use the built-in Error class as a genereal purpose container for more specialized exceptions. Update: This is not possible, either, because Error stringifies it's message parameter during initialization, instead of doing it as late as possible :(
Post a Comment