SHARE
Facebook X Pinterest WhatsApp

Handling JavaScript Errors by Type

Written By
thumbnail
Rob Gravelle
Rob Gravelle
May 24, 2012

There are four major error types in programming: compile errors, logic errors, input/validation errors, and runtime errors. Error catching in code is usually limited to the latter two types. It would be nice if you could handle your own logic errors at runtime, but sadly, there is no such code construct yet. As for syntax errors, an interpreted language like JavaScript won’t catch those until the script is loaded into and read by the browser. While you normally can’t catch syntax errors, as we’ll see shortly, there are times that you can. Today’s article will discuss the syntax error, along with two other error types, while the next installment will cover the remaining three.

The Six JavaScript Error Types

The JavaScript 1.5 specification defines six primary error types, as follows:

  • EvalError: Raised when the eval() functions is used in an incorrect manner.
  • RangeError: Raised when a numeric variable exceeds its allowed range.
  • ReferenceError: Raised when an invalid reference is used.
  • SyntaxError: Raised when a syntax error occurs while parsing JavaScript code.
  • TypeError: Raised when the type of a variable is not as expected.
  • URIError: Raised when the encodeURI() or decodeURI() functions are used in an incorrect manner.

The Error.name Property

The benefit of having all the different error types is that you can pinpoint more accurately what kind of error you’re dealing with. This is done using the Error.name property because JavaScript’s loose typing doesn’t support specifying which type you want to catch as you would in Java:

catch(ArrayIndexOutOfBoundsException e) {}

In JavaScript, you have to use an if statement within a single “catch” block:

try {
	execute this block
} catch (error) {
	if (error.name === 'RangeError')
  {
  	do this
  }
  else if (error.name === 'ReferenceError')
  {
  	do this
  }
  else
  {
  	do this for more generic errors
  }
}

I personally like to use a switch if I’m checking for several error types at once instead of ifs because the same error name property is evaluated every time.

Here’s an example that produces and catches a SyntaxError. The code execution is linked to a button click event using the eval() function. Although there is also an EvalError type, it doesn’t happen because the eval() is used correctly; it’s the code that’s dubious (notice the missing closing quote [“])! In fact, this error type is thrown pretty much exclusively from the eval() method because syntax errors stop code execution immediately. That means that you can often catch them in development and testing.

function captureSyntaxError() {
  try {
  	eval('alert("Hello world)');
  } 
	catch(error) {
		if (error.name === 'SyntaxError') {
  		alert("caught a " + error.name + ": " + error.message);
			//handle that error type
		}
		else {
			alert("caught a " + error.name + ": " + error.message);
			//handle generic errors here
		}
	}
}

This version also checks for an EvalError, so the if statement has been replaced by a switch. An EvalError is pretty rare as the only way to encounter it is to use the eval in any way other than a direct method call. So how do you do that? You can treat it like an object using the new keyword:

var y = new eval();

Setting it to a variable should also throw an EvalError:

eval = 'test';

You shouldn’t come across the EvalError all that often because Internet Explorer 8 and Firefox 4+ don’t seem to ever throw them! Both treat the first example as a TypeError and don’t mind setting eval to whatever you want, effectively clobbering it into oblivion!

function captureEvalError() {
  try {
  	var sum = eval('function test(( { return 1 + 1; }');
    alert("NO ERROR CAUGHT: Your browser doesn't seem to mind that we just set eval to the letter 'x'!");
	} catch(error) {
  	switch (error.name) {
  		case 'SyntaxError':
  			alert("caught a " + error.name + ": " + error.message);
  			//handle error…
  			break;
  		case 'EvalError':
  			alert("caught a " + error.name + ": " + error.message);
  			//handle error…
  			break;
  		default:
  			alert("caught a " + error.name + ": " + error.message);
  			//handle all other error types here…
  			break;
  	}
  } 
}

The ReferenceError

Reference errors are one of the most common of all. They’re caused by referencing a variable that has not been declared first. For instance:

var tmp = x; //no x variable declared!

Before trying the next demo, be aware that Internet Explorer 8 does not handle these correctly either, throwing a TypeError instead.

function captureReferenceError() {
  try {
  var sum = x + y;
    alert(sum);
	} catch(error) {
  	switch (error.name) {
  		case 'SyntaxError':
  			alert("caught a " + error.name + ": " + error.message);
  			//handle error…
  			break;
  		case 'EvalError':
  			alert("caught a " + error.name + ": " + error.message);
  			//handle error…
  			break;
        case 'ReferenceError':
  			alert("caught a " + error.name + ": " + error.message);
  			//handle error…
  			break;
  		default:
  			alert("caught a " + error.name + ": " + error.message);
  			//handle all other error types here…
  			break;
  	}
  } 
}

 

Conclusion

Today we learned how to distinguish between different error types using the Error.name property as well as three of the six JS error types. In the next article, we’ll be covering the RangeError, TypeError, and URIError types.

Recommended for you...

The Revolutionary ES6 Rest and Spread Operators
Rob Gravelle
Aug 23, 2022
Ahead of Time (AOT) Compilation in Angular
Tariq Siddiqui
Aug 16, 2022
Converting a JavaScript Object to a String
Rob Gravelle
Aug 14, 2022
Understanding Primitive Type Coercion in JavaScript
Rob Gravelle
Jul 28, 2022
HTML Goodies Logo

The original home of HTML tutorials. HTMLGoodies is a website dedicated to publishing tutorials that cover every aspect of being a web developer. We cover programming and web development tutorials on languages and technologies such as HTML, JavaScript, and CSS. In addition, our articles cover web frameworks like Angular and React.JS, as well as popular Content Management Systems (CMS) that include WordPress, Drupal, and Joomla. Website development platforms like Shopify, Squarespace, and Wix are also featured. Topics related to solid web design and Internet Marketing also find a home on HTMLGoodies, as we discuss UX/UI Design, Search Engine Optimization (SEO), and web dev best practices.

Property of TechnologyAdvice. © 2025 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.