Custom errors in JavaScript

JavaScript provides us with a collection of 8 error objects, which are raised in try/catch expressions based on the type of error. they are:

  • Error
  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

I'm hereJavaScript errorTutorial.

Here, I want to explain how to create your own custom error by extending the basic Error class:

class OutOfFuelError extends Error {}

class FlatTireError extends Error {}

Custom errors allow you to take different actions based on specific error types, without the need to use error messages to understand the type of error.

try {
  //some code
} catch (err) {
  if (err instanceof OutOfFuelError) {
    //handle error
  } else if (err instanceof FlatTireError) {
    //handle error
  }
}

Of course, before performing this operation, the error must be explicitly thrown in the code:

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

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

During error creation, you can also customize anything related to the class, and even the parameters received by the constructor when needed:

class OutOfFuelError extends Error {
  constructor(message) {
    super(message)
    this.name = "OutOfFuelError"
  } 
}

Download mine for freeJavaScript beginner's manual


More js tutorials: