Exception Handling in Javascript in 5 Minutes
Exception Handling in Javascript in 5 Minutes

For some reason while write code people always think only about happy path. In this video I will teach you how to handle errors in Javascript in less that 10 minutes.

To make you code robust you must always think in pessimistic way. How can my code break? How can I prevent it?

Here we are got a JSON from backend which we try to parse in Javascript object. Most beginners will assume after testing that it will work forever but actually it will break at the moment when we get invalid JSON.

const backendData = "{name: 'Jack'}";
const user = JSON.parse(backendData);

As you can see we get

Unexpected token n in JSON at position 1

because our JSON is invalid.

We can make our code safe by handling our error correctly.

let user;
try {
  const backendData = "{name: 'Jack'}";
  user = JSON.parse(backendData);
} catch (err) {
  user = null;
}

console.log(user);

So we wrapped our code in try catch block which means if we get any error in code inside try block we will jump to catch part. In this case to make our code bulletproof we can set user to null if we can't get it's data correctly.

So always if you are not sure if you code can break wrap it in try catch. The most popular cases are parsing JSON and async await.


One more thing that not a lot of people are using is finally. So actually try catch is not the full construction to handle errors

let user;
try {
  const backendData = "{name: 'Jack'}";
  user = JSON.parse(backendData);
} catch (err) {
  user = null;
} finally {
  console.log("i happen always");
}

console.log(user);

We use here finally block which will happen in both cases. When there no errors and when we go in catch. The common usage of finally is if you have the same logic in try and catch and you don't want to duplicate it. Then you just put it in finally.


The last important thing about error handling is throwing errors. It is a good practice to throw errors if you don't get correct parameters in your function or if data is invalid.

const updateUser = (id, data) => {
  if (!id || !data) {
    throw "Params are not correct";
  }
};

updateUser();

So we have here updateUser function which can't work without correct parameters. We must know the id of the user to update and what data we want to change. To make sure that everybody use our function correct and it will never break we can simply throw an error if some of params is missing.

As you can see in browser we don't even need to specify in what function it happened because we can see it directly in stacktrace.

It is super important to think about your code in pessimistic way and handle errors correctly before they happen.

Also if you want to improve your programming skill I have lots of full courses regarding different web technologies.

📚 Source code of what we've done