Custom error catcher in JavaScript

There are two error handling situations in JavaScript. Either an error is thrown from a third-party library, database, API or you want to throw an error yourself.

Make your own custom errors by extending the base Error class:

class OutOfError extends Error {}

class FlatError extends Error {}
try {
  //some code
} catch (err) {
  if (err instanceof OutOfError) {
    //handle error
  } else if (err instanceof FlatError) {
    //handle error
  }
}

Then you can throw error like this:

try {
  const car = new Car() //imagine we have a Car object

  if (!car.fuel) {
    throw new OutOfError('No fuel!')
  }
  if (car.flatTire) {
    throw new FlatError('Flat tire!')
  }
} catch (err) {
  if (err instanceof OutOfError) {
    //handle error
  } else if (err instanceof FlatError) {
    //handle error
  }
}