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
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.
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.
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With