Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-10-24 01:53:02
Original
478 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!