xinglinkedinenvelopebubblesgoogleplusfacebooktwitterfeedgithub

Error handling in JavaScript

31st January 2014 | by Adam Beres-Deak | javascript, browser, error, node.js

Have you ever wondered, what's the proper way of throwing JavaScript errors? And how to handle them? Here we'll see some examples and we'll define some custom error types.

Additional bonus: the following code examples also work in node.js not just in the browsers.

Throwing Errors

Throwing errors is very simple, we just need the throw statement.

function throwsAnError() {
    throw new Error('An error occured');
}

try {
    throwsAnError();
} catch(ex) {
    console.log(ex.message); // An error occured
}

Theoretically it's possible to throw any kind of object, but it's not really recommended throwing anything else than Error or one of its derived (custom) types. The reason for this is, that browsers not always work as you would expect. Some of them (IE, Safari) only show "uncaught exception" and don't show the object which was thrown.

Default error types in JavaScript

There are six predefined error types in JavaScript:

Handling specific errors

Here comes the instanceof operator handy, when our codes runs into a catch. With its help we can check which type does the exception belong to.

try {
    // doSomethingWithNumbersAndURIs();
} catch (ex) {
    if (ex instanceof RangeError) {
        alert('Value not in range!');
    } else if (ex instanceof URIError) {
        alert('Value not an URI!');
    } else {
        // some basic error handling
    }
}

Throwing custom errors

This is also very simple, we just have to create a constructor for our error type which is derived from Error. There's one little catch though, line numbers are shown incorrectly.

function CustomError(message) {
  this.name = "CustomError";
  this.message = message || "Some default message";
}
CustomError.prototype = new Error();
CustomError.prototype.constructor = CustomError;

try {
    throw new CustomError('An error occured!');
} catch(ex) {
    console.log(ex.name); // CustomError
    console.log(ex.message); // Ann error occured!
}

If you are interested in more details:

  1. Mozilla Developer Network Documentation
  2. NCZOnline

by Adam Beres-Deak

| Share | Tweet | Share | Share

Latest blog posts

Displaying icons with custom elements 14th October 2015

Plain JavaScript event delegation 26th January 2015

After the first year of blogging - what happened on my blog in 2014? 1st January 2015

Better webfont loading with using localStorage and providing WOFF2 support 18th December 2014

Worth watching: Douglas Crockford speaking about the new good parts of JavaScript in 2014 20th October 2014