Extending Error Objects in JavaScript
When throwing exceptions in JavaScript, one may desire to extend the built-in Error object to create custom error types. This allows for more specific and informative exception handling.
In JavaScript, Inheritance Isn't Through Subclassing
Unlike in Python, where exceptions are typically subclassed from the Exception base class, JavaScript does not support traditional subclassing for error objects. Instead, it utilizes the concept of prototype extension.
Extending Error Objects in ES6
In ES6, the extends keyword can be used to extend the Error object, creating a custom error constructor:
class MyError extends Error { constructor(message) { super(message); this.name = 'MyError'; } }
In this example, the MyError class inherits from the Error object and overrides the name property.
Creating Custom Exceptions
To create an instance of the custom error, simply instantiate it like any other object:
throw new MyError('Something went wrong');
Handling Custom Errors
When handling errors, you can use the instanceof operator to check for specific error types:
try { // ... } catch (err) { if (err instanceof MyError) { // Handle MyError specifically } else { // Handle other errors } }
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