【问题标题】:Why does Json's Stringify output print differently from console.log output?为什么 Json 的 Stringify 输出打印与 console.log 输出不同?
【发布时间】:2021-07-21 10:01:11
【问题描述】:

以下代码:

const testStringify = () => {
        try{
            console.log('Inside testStringify');
            const a = "";
            a.b.c;
        } catch(err) {
            console.log('Inside catch of testStringify');
            console.log(`Error: ${JSON.stringify(err)}`);
            console.log(err);
        }
    }
    
    testStringify();

输出是:

Inside testStringify
Inside catch of testStringify
Error: {}
TypeError: Cannot read property 'c' of undefined
    at testStringify
    at Object.<anonymous>
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3

为什么 Json.stringify(err) (Error: {}) 不以与 console.log(err) 相同或某种有意义的方式打印输出?

【问题讨论】:

    标签: javascript node.js json stringify


    【解决方案1】:

    JSON.stringify 仅迭代自己的和可枚举的属性。

    const obj = Object.create({ onProto: 'onProto' });
    Object.defineProperty(obj, 'notEnumerable', { value: 'notEnumerable' });
    obj.ownAndEnumerable = 'ownAndEnumerable';
    console.log(JSON.stringify(obj)); 

    在某些浏览器中,Error 对象的 .message 属性不是自己的可枚举属性,因此不会被迭代。

    例如,在 Chrome 中,该属性是自己的,但不可枚举:

    const e = new Error('msg');
    console.log(Object.getOwnPropertyDescriptor(e, 'message'));
    另一方面,

    console.log(err) 将在交互式控制台中显示完整对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2016-10-10
      相关资源
      最近更新 更多