包裹在反引号`${error}`中的错误对象打印方式不同

Error object printing differently when wrapped in Backtick `${error}`

Axios 用于进行第 3 方 REST 调用。经常收到 超时错误

axios({
          url,
          method: 'post',
          headers,
          data: xml,
          timeout,
          proxy,
        }).then((response) => {
          resolve(response);
        }).catch(error => {
          console.log(error);    // prints big object
          console.log(${error}); // prints just a line
        });




如果我通过 console.log() 打印超时错误,它会打印如下:

{
  "name": "insurance-service",
  "hostname": "adi",
  "pid": 30101,
  "level": "FATAL",
  "err": {
    "message": "timeout of 30000ms exceeded",
    "name": "Error",
    "stack": "Error: timeout of 30000ms exceeded\n    at /home/adi/workspace/insurance-service/dist/modules/health_insurance/providers/hdfc/optimarestore/integration.js:139:23\n    at Parser.<anonymous> (/home/adi/workspace/insurance-service/node_modules/xml2js/lib/parser.js:304:18)\n    at Parser.emit (events.js:315:20)\n    at Parser.EventEmitter.emit (domain.js:483:12)\n    at SAXParser.onclosetag (/home/adi/workspace/insurance-service/node_modules/xml2js/lib/parser.js:262:26)\n    at emit (/home/adi/workspace/insurance-service/node_modules/sax/lib/sax.js:624:35)\n    at emitNode (/home/adi/workspace/insurance-service/node_modules/sax/lib/sax.js:629:5)\n    at closeTag (/home/adi/workspace/insurance-service/node_modules/sax/lib/sax.js:889:7)\n    at SAXParser.write (/home/adi/workspace/insurance-service/node_modules/sax/lib/sax.js:1436:13)\n    at Parser.exports.Parser.Parser.parseString (/home/adi/workspace/insurance-service/node_modules/xml2js/lib/parser.js:323:31)\n    at Parser.parseString (/home/adi/workspace/insurance-service/node_modules/xml2js/lib/parser.js:5:59)\n    at Object.exports.parseString (/home/adi/workspace/insurance-service/node_modules/xml2js/lib/parser.js:369:19)\n    at HDFCOptimaRestore.getErrorResultFromProposalXml (/home/adi/workspace/insurance-service/dist/modules/health_insurance/providers/hdfc/optimarestore/integration.js:132:26)\n    at /home/adi/workspace/insurance-service/dist/modules/health_insurance/providers/hdfc/optimarestore/integration.js:119:26\n    at processTicksAndRejections (internal/process/task_queues.js:97:5)"
  },
  "msg": "timeout of 30000ms exceeded",
  "src": {},
  "v": 0,
  "timestamp": "2021-05-10T06:50:26.211Z"
}

但是,如果我像 ${error} 那样做,它只会打印一行,如下所示。 [这里error是catch()的参数]

Error: timeout of 30000ms exceeded

为什么这两个行为不同?

console.log(error);

打印整个对象。

console.log(`${error}`);

打印字符串表示形式 (Object.prototype.toString / Error.prototype.toString)。

这是由于 console.log 的特殊行为。

当您向它传递一个对象时,整个对象 将被记录下来,可以从浏览器控制台进行导航和扩展 - 以便于调试。

当您将其转换为带有模板文字的字符串时,只会显示该静态字符串

显然

Error: timeout of 30000ms exceeded

是将 Error 对象强制转换为字符串的结果。