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(e.constructor.name); // 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
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

  • By
    How to Create a Twitter Card

    One of my favorite social APIs was the Open Graph API adopted by Facebook.  Adding just a few META tags to each page allowed links to my article to be styled and presented the way I wanted them to, giving me a bit of control...

Incredible Demos

Discussion

  1. Damien Maillard

    I use e.name === '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!