Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the actual output of console.log(error) and how do I get the exact same output as a string?

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.

like image 224
cprcrack Avatar asked Nov 29 '25 09:11

cprcrack


1 Answers

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);
  …
}
like image 115
Bergi Avatar answered Nov 30 '25 23:11

Bergi