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:
<code class="js">class MyError extends Error { constructor(message) { super(message); this.name = 'MyError'; } }</code>
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:
<code class="js">throw new MyError('An error occurred');</code>
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.
The above is the detailed content of How to Extend the Built-in Error Object in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!