console.error()

A quick tip on how to use the console.error() method from the Google Chrome Devtools API.

console.error()

Here's a ⚡️quick tip on how to clearly display errors within the Google Chrome Console using console.error().

Adding console.error() to your code

The Chrome Console is definitely one of the most useful tools when creating web apps, and the console.log() method is an absolute must when you're trying to see what exactly is going on with your code. It's nice to get a log of everything going on under the hood, but what if errors in your console logs became a little more clear?

Today, I introduce you to the console.error() method which allows you to define a custom error message and provides you with a stack trace back to the error itself.

Syntax

console.error(errorMsg);

The syntax is pretty straight forward. Just provide a custom error message for when some kind of undesired behavior happens and voilâ! A wild error appeared.

Example

Let's create a 'clock-in' function that allows an employee to enter their idNumber in order to clock in for their shift. It will throw an error, however, if the employee tries to enter name instead:

var employee = { name: 'Elon Musk', idNumber: 897456, occupation: 'Engineer' }

function clockIn(employeeIdNumber) {

	if (typeof employeeIdNumber === "string") {
		console.error('Please clock-in using your ID number!');
	} 

	if (typeof employeeIdNumber === 'number') {
		console.log('Thank you for clocking in!')
	}

}

clockIn(employee.name); // throws an error

Try this the code snippet in your browser console.

The Output

There you have it! If everything went as planned (sort of?), you should see the custom error in the console like so:

codesnippet-console-error

The console.error() super handy when it comes to making sure your data is doing what it should be!

Stay Tuned 📺

There's a ton of other useful methods in the Google Chrome Devtools API. We will be posting more ⚡️quick tips in the coming weeks!

If you have any questions or improvements, or if you'd like to see additional examples, feel free to reach out to me anytime at [email protected]. If you're enjoying my posts, please subscribe below! 👇

Help us improve our content