Javascript 使用反勾号“${Error}包装时以不同方式打印对象时出错`

Javascript 使用反勾号“${Error}包装时以不同方式打印对象时出错`,javascript,typescript,error-handling,Javascript,Typescript,Error Handling,Axios用于拨打第三方REST电话。此时通常会收到超时错误 axios({ url, method: 'post', headers, data: xml, timeout, proxy, }).then((response) => { resolve(response); }).catch(error => {

Axios用于拨打第三方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"
}

为什么这两个行为不同

console.log(error);
打印整个对象

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

打印字符串表示形式(/)。

这是由于控制台.log的特殊行为造成的

当您向它传递一个对象时,整个对象都将被记录,这将是可导航的,并且可以从浏览器控制台进行扩展,以便于调试

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

显然

Error: timeout of 30000ms exceeded

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

您正在将错误转换为字符串
Error: timeout of 30000ms exceeded