JavaScript Exception Handling HowTo

A very used paradigm when it come with dealing with errors is the try/catch construct.

In JavaScript you can throw anything as an exception, and in your catch statement you will receive that object instance that you threw. This is pretty cool, because when you receive the catched object, it might contain valuable information on what actually went wrong. In most cases though people just pass a string with the error message.

I've seen advanced programmers actually throwing the message itself as the thrown object, in code that I will simplify as this:

Unfortunately this is a problem, since we got the error message, and it looks good in our 7 lines of code. In reality if our program was a bit bigger, our message was now meaningless, since we would need to find from where the thing was thrown. If the code that can cause the catastrophic failure is called from multiple sites, this only adds to the complexity.

This is why you always use the Exception object. The Exception object is part of standard JavaScript, and in all browsers, Chrome, Firefox, and IE from version 10 onwards (no one uses IE9 on their space ship anyway) has an extra property, named stack, that gives you the stack trace:

1

2

3

4

5

6

7

8

try{console.log("computer reports heating at engine 1.");thrownewError("oh man, catastrophic failure at engine 1.");}catch(e){console.log(e.stack);console.error("the pilot warning message was:",e);console.log('the time backtrack saving device went back in time and send a bot to fix the engine.');}