Lov*_*edi 2 javascript json node.js stringify
对于以下代码:
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();
Run Code Online (Sandbox Code Playgroud)
输出是:
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
Run Code Online (Sandbox Code Playgroud)
为什么 Json.stringify(err) (错误:{})不以与 console.log(err) 相同的方式或某种有意义的方式打印输出?
JSON.stringify仅迭代自己的和可枚举的属性。
const obj = Object.create({ onProto: 'onProto' });
Object.defineProperty(obj, 'notEnumerable', { value: 'notEnumerable' });
obj.ownAndEnumerable = 'ownAndEnumerable';
console.log(JSON.stringify(obj)); Run Code Online (Sandbox Code Playgroud)
在某些浏览器中,.messageError 对象的属性不是自己的可枚举属性,因此不会对其进行迭代。
例如,在 Chrome 中,该属性是自己的但不可枚举:
const e = new Error('msg');
console.log(Object.getOwnPropertyDescriptor(e, 'message'));Run Code Online (Sandbox Code Playgroud)
console.log(err)另一方面,将在交互式控制台中显示完整的对象。
| 归档时间: |
|
| 查看次数: |
493 次 |
| 最近记录: |