简体   繁体   中英

JavaScript ES6 - console.log with template literal

I'm writing node's script that connect to the mongo database.

I noticed that printing error response is different by small change in console.log syntax. Below example should be more meaningful.

#!/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`)
    }
});

Example output of the first console.log

MongoError: Authentication failed.

Example output of the second 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.' }

Where comes from this difference?

${err} (or '' + err for that matter) will interpolate the err object with a string which will also change your Error object into a string - which is equivalent to calling err.toString() . However directly logging err will pass it to the console as an object and display it in that manner.

This is called "implicit coercion" - if you would like to know more about this subject I can highly recommend reading You Don't Know JS: Types & Grammar (Chapter 4: Coercion) for a deep dive.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM