How to handle specific errors in JavaScript?

Sometimes, we want to handle specific errors in JavaScript.

In this article, we’ll look at how to handle specific errors in JavaScript.

How to handle specific errors in JavaScript?

To handle specific errors in JavaScript, we use the instanceof operator.

For instance, we write

try {
  //...
} catch (e) {
  if (e instanceof SpecificError) {
    // ...
  } else {
    throw e;
  }
}

to check if e in the catch block is an instance of the SpecificError constructor with

e instanceof SpecificError

Then we do what we want if that’s true.

Conclusion

To handle specific errors in JavaScript, we use the instanceof operator.