gpt4 book ai didi

node.js - Node.js 中的 Error 类

转载 作者:太空宇宙 更新时间:2023-11-03 22:11:50 25 4
gpt4 key购买 nike

显然在 Node 文档的控制台核心模块( https://nodejs.org/dist/latest-v4.x/docs/api/console.html )中存在以下代码:

console.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to stderr

但是,当我运行 test.js 时,代码如下所示

var err = new Error('a');
console.error(err);

终端打印如下消息:

Error: a at Object. (/Users/suoyong/Express/连接数据库/error.js:1:73) at Module._compile (module.js:556:32) at Object.Module._extensions..js (module.js:565:10) at Module.load (module.js:473:32) at tryModuleLoad (module.js:432:12) at Function.Module._load (module.js:424:3) at Module.runMain (module.js:590:10) at run (bootstrap_node.js:394:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:509:3

正如你所看到的,我的代码与 Node 文档相同,但结果却不同。请帮我解决这个小问题。

最佳答案

console.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to stderr

这不是字面意义上的解释。无论如何,最新的 LTS 和稳定版本中没有。打印这样的错误实际上会打印错误对象的文本表示,这在文档中被称为[Error: Whoops, Something bad gone]Console.error() 的文档进一步阐明了实际的预期行为。 :

If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated.

util.inspect() 方面,此方法“返回主要用于调试的对象的字符串表示形式”。对于 Error 类型的对象,这将生成一个包含错误消息和堆栈跟踪的字符串。

> const txt = util.inspect(new Error("I'm on SO"))
undefined
> txt
'Error: I\'m on SO\n at repl:1:26\n at sigintHandlersWrap (vm.js:22:35)\n at sigintHandlersWrap (vm.js:96:12)\n at ContextifyScript.Script.runInThisContext (vm.js:21:12)\n at REPLServer.defaultEval (repl.js:313:29)\n at bound (domain.js:280:14)\n at REPLServer.runBound [as eval] (domain.js:293:12)\n at REPLServer.<anonymous> (repl.js:513:10)\n at emitOne (events.js:101:20)\n at REPLServer.emit (events.js:188:7)'
> console.log(txt)
Error: I'm on SO
at repl:1:26
at sigintHandlersWrap (vm.js:22:35)
at sigintHandlersWrap (vm.js:96:12)
at ContextifyScript.Script.runInThisContext (vm.js:21:12)
at REPLServer.defaultEval (repl.js:313:29)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
at REPLServer.<anonymous> (repl.js:513:10)
at emitOne (events.js:101:20)
at REPLServer.emit (events.js:188:7)

关于node.js - Node.js 中的 Error 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40023550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com