In a Node.js project using Typescript and targeting ES2020, I'm using a custom Error class like this:
class InvalidParamsError extends Error {
}
try {
throw new InvalidParamsError();
} catch (error) {
if (error instanceof Error) {
console.log(error);
console.log(error.message); // Different output
console.log(error.stack); // Different output
console.log(error.toString()); // Different output
}
}
The output I get in the console is:
InvalidParamsError
at REPL11:2:13
at ...
Error
at REPL11:2:13
at ...
Error
undefined
How can I get this very same output as a string without having to print it to the console?
error.message
, error.stack
and error.toString()
all return different strings, and none of them show InvalidParamsError
as part of the output, showing a generic Error
instead. I know I could fix this manually setting the name
of the InvalidParamsError
in the constructor, but even then I'm unable to get exactly the same output as console.log(error)
as a string.
I tried looking at Node.js' console source code but couldn't find any answer.
I'm targeting ES2020 so I don't think this is related with previous Typescript issues when extending built-ins like Error.
from What is the actual output of console.log(error) and how do I get the exact same output as a string?
No comments:
Post a Comment