"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Extend the Built-in Error Object in JavaScript?

How to Extend the Built-in Error Object in JavaScript?

Published on 2024-11-03
Browse:376

How to Extend the Built-in Error Object in JavaScript?

Extending Error in JavaScript

To extend the built-in Error object in JavaScript, you can define a subclass of Error using the extends keyword. This allows you to create custom errors with additional properties or methods.

In ES6, you can define a custom error class as follows:

class MyError extends Error {
  constructor(message) {
    super(message);
    this.name = 'MyError';
  }
}

This class inherits the properties and methods of the Error class, and adds a custom name property. You can throw an instance of this custom error using the throw keyword:

throw new MyError('An error occurred');

The resulting error will be an instanceof Error, but it will also have the additional name property. This allows you to handle custom errors differently in your code, if needed.

Release Statement This article is reprinted at: 1729678050 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3