console.log格式化的错误对象不同于error.prototype.toString

console.log formats error object different from Error.prototype.toString

本文关键字:不同于 error prototype toString 对象 错误 log 格式化 console      更新时间:2023-09-26

我在这里看到Error.prototype.toString实现。

它主要将error.nameerror.message打印为name + ': ' + msg

但当我将Error对象传递给console.log时,我看到file not exists错误将更多属性打印为errno, code, syscall等。

console.log调用什么来打印Error对象的字符串摘要?

代码:

var fs = require('fs')
fs.readFile('/abcd', 'utf8', function(err, res){
  console.log("the error toString method shows, " + err)
  console.log("the console log's string summary is,")
  console.log(err)
})

输出:

the error toString method shows, Error: ENOENT: no such file or directory, open '/abcd'
the console log's string summary is,
{ [Error: ENOENT: no such file or directory, open '/abcd'] errno: -2, code: 'ENOENT', syscall: 'open', path: '/abcd' }

console.log未指定,因此每个浏览器都实现了不同的功能。(Node.js也是如此。)如果你想知道确切的内容,你可以看看浏览器的源代码,当然除了IE/Edge。

在Node.js中,我假设您使用它是因为require,代码是:

  • console.log调用util.format
  • util.format调用内部inspect函数
  • 它调用内部CCD_ 11函数
  • 在这种情况下调用内部CCD_ 12函数
    • 调用大括号包围的CCD_ 13
    • 而且还调用沿着可见密钥传递的formatter,从而提供额外的比特