console.log(error) 的实际输出是什么?我如何将其完全相同的输出作为字符串获取?

3
在一个使用 Typescript 并且目标为 ES2020 的 Node.js 项目中,我正在使用自定义 Error 类如下所示:
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
  }
}

我在控制台中得到的输出是:

InvalidParamsError
    at REPL11:2:13
    at ...

Error
    at REPL11:2:13
    at ...
Error
undefined

如何将此输出作为字符串获取,而无需将其打印到控制台?

error.messageerror.stackerror.toString() 都返回不同的字符串,而且没有一个显示 InvalidParamsError 作为输出的一部分,而是显示一个通用的 Error。我知道我可以通过在构造函数中手动设置 InvalidParamsErrorname 来修复这个问题,但即使这样,我也无法像字符串一样精确地获得与 console.log(error) 相同的输出。

我尝试查看 Node.js 的控制台源代码,但找不到任何答案。

我正在针对 ES2020,因此我认为这与 扩展内置类型(如 Error)时出现的先前 TypeScript 问题无关


error.toString()? - undefined
1
@ScottMarcus 这就是帖子的重点,它会产生不同的输出。 - undefined
@ScottMarcus你有没有读问题的内容?error.toString()的输出文本中并不包含InvalidParamsError,我已经尝试过了。而且,在Error类型中并不存在属性'type'。 - undefined
这个回答解决了你的问题吗? 在node.js中捕获console.log? - undefined
@BenWheeler 如果我的答案够权威的话,请告诉我 - undefined
显示剩余2条评论
3个回答

0
我觉得这就是你在找的东西。
try {
  throw new InvalidParamsError();
} catch (e) {
  console.log(
    `Uncaught ${e.constructor.name}: ${e.message}\n${e.stack
      .split("\n")
      .filter((item) => item)
      .map((item) => "  " + item)
      .join("\n")}`
  );
}

0
我尝试查看Node.js的控制台源代码,但找不到任何答案。
在node.js中,console.log使用了util.format,而util.format又依赖于util.inspect。该函数的代码经过一些复杂的处理,最终调用formatError函数,从而生成了你所需要的输出。
特别是在improveStack中,关于使用InvalidParamsError名称的部分,它将error.stack的标准起始部分替换为由getConstructorNamegetPrefix创建的标准对象检查前缀(例如Array(n)Object)。

我如何以字符串形式获得与此完全相同的输出,而无需将其打印到控制台?

import { inspect } from 'node:util';

class InvalidParamsError extends Error {}

try {
  throw new InvalidParamsError();
} catch (error) {
  const string = inspect(error);
  …
}

-1
要获取此输出的字符串版本:
if (error instanceof Error) {
    // remove the first line of the stack
    const errorStackLines = error.stack.split('\n')
    errorStackLines.splice(0,1)
  
    const stackWithoutErrorName = stackLines.join('\n')
    const errorName = error.constructor.name
    const { message, stack } = error

    const errorString = `${errorName}\n${stackWithoutErrorName}\n${message}\n${stack}\n${error.toString()}`

    return errorString
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接