Error Handling in JavaScript: a Quick Guide

Is There a Right Way to Get Stuff Wrong?

Bret Cameron
The Startup

--

There is no such thing as perfect code. Even if there was, our users will always find surprising ways to break what once seemed like perfectly watertight code and attempt to do things that we don’t want them to! How do we control these perilous situations? Using errors!

In this article, we’ll look into error handling in JavaScript. We’re specifically talking about runtime errors — sometimes called execution errors. These are the errors that occur while our programming is running: if they’re not caught, then they’ll typically crash our programs, something we usually want to avoid! By the end of the article, you’ll have seen several different approaches to error handling in JavaScript, as well as several ways to extend JavaScript’s built-in Error to make it more useful.

But first, a thorny question…

Should I use throw, return or console.error?

This is the question that inspired me to write this article. I wanted to know the best practices around when we should throw an error, when we should use return , and when console.error should come in.

Even if you’re new to JavaScript, you should have a decent understanding of return . You may not have…

--

--

Bret Cameron
The Startup

Writer and developer based in London. On Medium, I mainly write about JavaScript, web development and Rust 💻