How can I rethrow an error or exception in nodejs/javascript and include a custom message.
I have the following code
var json = JSON.parse(result);
and I wanted to include the result
content in the exception message should any parsing error occurs. Something like this.
1. try {
2. var json = JSON.parse(result);
3. expect(json.messages.length).to.be(1);
4. } catch(ex) {
5. throw new Error(ex.message + ". " + "JSON response: " + result);
6. }
The problem here is that I lose my stack trace.
Is there a way to do it similar to java
?
throw new Error("JSON response: " + result, ex);
ES2022 added the
.cause
non enumerable property toError
objects which can be set from the constructorSupported in:
From the tc39 proposal, there is an es-shim
Error
implementation and how the cause property is set.See Scotty Jamison's answer for more stack trace detail
Answer prior to 2022
I'm not aware of a native method like Java's and I've not found an elegant solution for wrapping errors yet.
The problem with creating a
new Error
is you can lose metadata that was attached to the originalError
that was thrown, the stack trace and type are generally the important items lost.Making modifications to an existing thrown error is quicker, but it is still possible to modify data from the error out of existence. It also feels wrong to be poking around in an error that was created somewhere else.
Create a new Error and new stack
The
.stack
property of a newError
is a plain string and can be modified to say what you like before it is thrown. Replacing an errorsstack
property completely can get really confusing for debugging though.When the original thrown error and the error handler are in separate locations or files (which is common with promises), you might be able to trace the source of the original error but not trace the handler where the error was actually trapped. To avoid this it's good to keep some references to both the original and new error in the
stack
. It's also useful to have access to the complete original error if there was additional metadata stored in it.Here's an example of catching an error, wrapping it in a new error but adding the original
stack
and storing theerror
:Which throws:
So we've created a new generic
Error
. Unfortunately the type of the original error becomes hidden from the output but theerror
has been attached as.original_error
so it can still be accessed. The newstack
has been largely removed except for the generating line which is important, and the original errorsstack
appended.Any tools that try to parse stack traces might not work with this change or best case, they detect two errors.
Rethrowing with ES2015+ Error Classes
Making this into a reusable ES2015+ Error class:
Results in
Then you know that whenever you see a
RethrownError
that the original error will still be available at.original_error
.This method is not perfect but it means I can re-type known errors from underlying modules into generic types that be handled more easily, usually with bluebirds filtered catch
.catch(TypeError, handler)
Note
stack
becomes enumerable hereSame Error with a modified stack
Some times you will need to keep the original error mostly as is.
In this case you can just append/insert the new info onto existing stack.
Which returns
Also note that the stack processing is simple and assumes the error message is a single line. If you run into multi line error messages you might need to look for
\n at
to terminate the message.