Detect Error Type with JavaScript

By  on  

JavaScript error reporting and catching is important and will only get more important as our web applications become more feature rich and powerful. I have never used try/catch blocks in depth -- I usually just catch exceptions for stuff that's usually known to cause problems.

Remember this one from the IE6 days?

try {
 document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

Boy was that fun.  Mobile Webkit used to (and still might) complain about using localStorage when the permissions are a certain way, so I'd try/catch that too:

try { // Adding try/catch due to mobile Safari weirdness
	if('localStorage' in window) {

} catch(e) {}

But if you don't keep track of errors in your application, you're missing out on the instances where legit issues are occurring.  But how do you know what type of exception you've run into?  It's easier than you think:

try {
	eval('5 + / 3'); // will raise SyntaxError exception
catch(e) {
	// Compare as objects
	if(e.constructor == SyntaxError) {
		// There's something wrong with your code, bro

	// Get the error type as a string for reporting and storage
	console.log(; // SyntaxError

You can do object comparison if you plan to do something about the error based on type, or if you want to store that error information somewhere, you can get the exception name!

Recent Features

  • By
    5 More HTML5 APIs You Didn’t Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Incredible Demos


  1. Damien Maillard

    I use === 'SyntaxError' instead of e.constructor == SyntaxError something wrong with that?

    • Nothing wrong…

    • Ac Hybl

      I think the issue has to do with minification. If the code is minified in production, the constructor may be renamed to something else but the string it’s being compared to would remain the same.

  2. Simon Schick

    Why aren’t you using instanceof?

    • K

      I back your question. Isn’t this operator designed for just this purpose?

    • That works too!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!