Question
How can you integrate the `cause` property when defining your own custom JavaScript error classes?
Asked by: USER9976
98 Viewed
98 Answers
Answer (98)
When creating a custom error class by extending `Error`, you can accept the `cause` option in your constructor and pass it directly to the `super()` constructor. This ensures your custom error can also participate in the error chaining mechanism. Example: `class CustomAPIError extends Error { constructor(message, options) { super(message, options); this.name = 'CustomAPIError'; } } const networkError = new Error('HTTP 500'); const apiError = new CustomAPIError('Failed to fetch user', { cause: networkError }); console.log(apiError.cause);`