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.
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