2

我正在编写连接到 mongo 数据库的节点脚本。

我注意到打印错误响应因console.log语法的微小变化而有所不同。下面的例子应该更有意义。

#!/usr/bin/env node

const mongoose = require("mongoose");
const config = require("./config");

mongoose.connect(config.dbURI, (err) => {
    if (err) {
        console.log(`${err}`); // First console.log
        console.log(err); // Second console.log
    } else {
        console.log(`Database connection successful`)
    }
});

第一个示例输出console.log

MongoError: Authentication failed.

第二个示例输出console.log

{ MongoError: Authentication failed.
    at Function.MongoError.create (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/error.js:31:11)
    at /Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:489:72
    at authenticateStragglers (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:435:16)
    at Connection.messageHandler (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/pool.js:469:5)
    at Socket.<anonymous> (/Users/sigo/Sources/crypto-change/node_modules/mongodb-core/lib/connection/connection.js:321:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at Socket.Readable.push (_stream_readable.js:136:10)
    at TCP.onread (net.js:563:20)
  name: 'MongoError',
  message: 'Authentication failed.',
  ok: 0,
  code: 18,
  errmsg: 'Authentication failed.' }

这种差异从何而来?

4

2 回答 2

2

${err}(或'' + err就此而言)将err使用字符串插入对象,这也会将您的Error对象更改为字符串 - 这相当于调用err.toString()。但是,直接记录err会将其作为对象传递到控制台并以这种方式显示。

这被称为“隐式强制”——如果你想了解更多关于这个主题的信息,我强烈建议你阅读你不知道的 JS:类型和语法(第 4 章:强制)以深入了解。

于 2017-03-30T16:05:57.443 回答
2

By interpolating in a template string, the err object is cast to a string, using its own .toString method that is inherited from Error.prototype.toString. The code is equivalent to

console.log(String(err));
console.log(err.toString());

When passing the err object directly to the console.log method, it uses node's inspect function instead, the code is equivalent to

console.log(util.inspect(err));
于 2017-03-30T16:09:18.337 回答