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.
I tried looking at Node.js' console source code but couldn't find any answer.
In node.js console.log does use util.format which in turn defers to util.inspect. The code of that function jumps through some hoops but eventually calls the formatError function which creates the output you are looking for.
In particular, the bit about using the InvalidParamsError name happens in improveStack, where it replaces the standard error.name that the error.stack starts with by the standard object inspection prefix (e.g. Array(n) or Object) created from getConstructorName and getPrefix.
How can I get this very same output as a string without having to print it to the console?
import { inspect } from 'node:util';
class InvalidParamsError extends Error {}
try {
throw new InvalidParamsError();
} catch (error) {
const string = inspect(error);
…
}
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