Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good way to extend Error in JavaScript?

I want to throw some things in my JS code and I want them to be instanceof Error, but I also want to have them be something else.

In Python, typically, one would subclass Exception.

What's the appropriate thing to do in JS?

like image 351
Josh Gibson Avatar asked Sep 05 '09 00:09

Josh Gibson


People also ask

How do you handle errors in JavaScript?

JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#. try: wrap suspicious code that may throw an error in try block. catch: write code to do something in catch block when an error occurs.

Should you throw errors in JavaScript?

It's best to avoid throwing errors from inside a Promise, because they may not always be caught, depending on how the code that called them is structured. However it's good practice to return an error when rejecting a Promise, and you can return Error custom types just like any other Error.


1 Answers

In ES6:

class MyError extends Error {   constructor(message) {     super(message);     this.name = 'MyError';   } } 

source

like image 197
Mohsen Avatar answered Oct 17 '22 04:10

Mohsen