Menu Home

Error()

Hi everyone, and welcome to another exciting edition of Boring JavaScript! Today, we tackle the Error() object – and how you can create your own errors!

Don’t like to read? Then watch the video.

Whoops! I Did It Again!

Error() objects in JavaScript are a set of objects that come into play whenever there is an error that is thrown by JavaScript – say, for example, trying to get a property from an undefined object. Let’s take a look at a simple error:

const number = 123.45;
const formattedNumber = number.toFixed(-1);
console.log(formattedNumber);

/* output
const formattedNumber = number.toFixed(-1);
                               ^

RangeError: toFixed() digits argument must be between 0 and 100
    at Number.toFixed (<anonymous>)
    at Object.<anonymous> (
    ...and so on
*/

The above is an example of a RangeError, one of the eight error objects available in JavaScript.

But the above code does just about nothing to show us what an Error object is. After all, it stopped execution of the code and printed out a lot of information to the screen. So where is the object?

To Catch A Thief

When JavaScript creates an Error object (one of of the other seven objects derived from Error), it then has a decision to make. It eithers stops execution of the program (like above), or it gives it back to the application to process.

We want our application to ‘catch’ that error, so that we can examine the Error object. Let’s modify our code above:

let formattedNumber;
try {
	formattedNumber = number.toFixed(-1);
} catch(err) {
	console.log('Hey! Wrong number! Here are the details:');
	console.log(`Message:\t${err.message}`);
	console.log(`Name:\t\t${err.name}`);
	console.log(`Stack:\n${err.stack}`);
}

/* output
Hey! Wrong number! Here are the details:
Message:        toFixed() digits argument must be between 0 and 100
Name:           RangeError
Stack:
RangeError: toFixed() digits argument must be between 0 and 100
    at Number.toFixed (<anonymous>)
    at Object.<anonymous> (
    ...and so on
*/

When we use a ‘try/catch’ block, we are instructing that if something goes wrong with our code, then let the application process the error. ‘try/catch’ go together – if any code executed in the ‘try’ block fails, the error object is passed to the ‘catch’ block with the argument being the error object. From there, we can process the error by examining the properties of that object, as seen in the console.log() statements.

Custom Van Conversion

What if the errors given to you by JavaScript don’t meet your needs? What if you wanted to throw your own errors specific to your application? By using class inheritance, you can create your own customizable error messages.

And it’s very easy to do. Here is a class definition on a custom error message for our application:

class CannotAddAnimalError extends Error {
	constructor(animal) {
		super();
		this.message = `Animal type "${animal.type}" is not accepted at the zoo.`;
		this.name = 'CannotAddAnimalError';
	}
}

The key here is in Line 1 – and that is we ‘extend’ the base Error class to create our own class. Within our class, we then set the important properties for this error object – namely the ‘message’ of the error and the ‘name’ of the error.

And how does it get used? Just like any other error:

const processAnimal = (animal) => {
	let status = '';
	try {
		if (animal.type === 'Coyote') {
			throw new CannotAddAnimalError(animal);
		};
		status = `Welcome ${animal.name} the ${animal.type} to the zoo.`;
	} catch (err) {
		status = processError(err, animal);
	}
	return status;
}

If the animal we’re going to process is a ‘Coyote’ (Line 4), we simply throw a new ‘CannotAddAnimalError’ – which is our new Error object. By passing it the data that was being processed (animal), we can even further customize the error message (see the previous code snippet, Line 4).

Our ‘catch’ statement runs a function that processes the error, where we use the ‘name’ property to do different things based upon the type of error received. This allows us to process different types of errors (if we expect different errors to appear).

const processError = (err, animal) => {
	let errorMessage = '';
	switch(err.name) {
		case 'CannotAddAnimalError':
			errorMessage = `\n****WARNING: There is a ${animal.type} in the transfer vehicle!\n****${err.message}\n`;
			break;
		default:
			errorMessage = `**WHOOPS! We have a STRANGE animal (${animal.type}) on the transfer vehicle.`;
			break;
	}
	return errorMessage;
}

The ‘switch’ statement above is where we decide what to do based upon the type of error message we have received.

So if you run the application, you will get an output like this:

/* output
Welcome Fluffy the Cat to the zoo.
Welcome Fido the Dog to the zoo.
Welcome Mr. Ed the Horse to the zoo.
Welcome Betsy the Cow to the zoo.

****WARNING: There is a Coyote in the transfer vehicle!
****Animal type "Coyote" is not accepted at the zoo.

Welcome Beep Beep the Road Runner to the zoo.
Welcome Flipper the Dolphin to the zoo.
Welcome Moby Dick the Whale to the zoo.
Welcome Larry the Lizard to the zoo.
*/

You can see all of the code in our video and Github repository.

The Video

As always, we have a video that goes into detail on how to use the Error() object.

Shameless Plug

You can find us everywhere!

Check out all our videos at: https://www.boringjavascript.com

Github Repository: https://github.com/TheVirtuoid/boringjavascript

Check out everything at: https://www.thevirtuoid.com

Facebook: https://www.facebook.com/TheVirtuoid

Twitter: https://twitter.com/TheVirtuoid

YouTube: https://www.youtube.com/channel/UCKZ7CV6fI7xlh7zIE9TWqgw

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: