Home >Web Front-end >JS Tutorial >How to Extend the Built-in Error Object in JavaScript?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 01:53:02554browse

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:

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn