Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Error cause in JavaScript (node.js)

is it possible to specify the cause of an Error in JavaScript (node.js)? I found the Mozilla documentation which defines how to set the message / file / line but not the cause of an error.

The reason I'm interested in this is that I want to catch an internal error and propagate it to the surface in a nested exception (similar to exception chaining in Java).

Edit: I just found the following answer on stackoverflow on how to chain exceptions. Is that really all you can do?

-- ooxi

like image 736
ooxi Avatar asked Mar 10 '14 14:03

ooxi


People also ask

How do you declare errors in node JS?

The new Error() method is an inbuilt application programming interface of the Node module in which a new Error object is created and error. message property is set to the provided text message. By calling message. toString(), the text message is generated if an object is passed as a message.

What is type error in node JS?

The TypeError object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. A TypeError may be thrown when: an operand or argument passed to a function is incompatible with the type expected by that operator or function; or.


1 Answers

2022 update: Thanks to a TC39 proposal, it's now possible to specify error cause in javascript, like this:

try {
  operation();
} catch (error) {
  throw new Error("An error has occurred while doing operation", { cause: error });
}

feature available on plateforms: Node.js (16.9+), Chrome (93+), Firefox (91+) and Safari (15+)

I wrote a more detailed article here ;)

like image 164
Moaad FATTALI Avatar answered Nov 24 '22 08:11

Moaad FATTALI