Try/catch将错误对象保存到不在javascript中工作的文件

Try/catch将错误对象保存到不在javascript中工作的文件,javascript,Javascript,所以我有一个try-catch循环,当我得到一个错误时,我想把它保存为一个json文件。但是,该文件作为空对象返回 try{ //some error } catch(e){ fs.writeFileSync('err.json', JSON.stringify(e, null, 2), err=>{if(err)console.log(err)}) /// => {} } 我可以将错误记录到console.log中,它会很好地打印出来。在duckduckgo上似乎

所以我有一个try-catch循环,当我得到一个错误时,我想把它保存为一个json文件。但是,该文件作为空对象返回

try{
    //some error
} catch(e){
    fs.writeFileSync('err.json', JSON.stringify(e, null, 2), err=>{if(err)console.log(err)}) /// => {}
}
我可以将错误记录到console.log中,它会很好地打印出来。在duckduckgo上似乎没有关于这件事的任何信息,所以我想在这里问一下。

这是答案:

var util = require('util')

try{
     //some error
} catch(e){
    fs.writeFileSync('err.json', util.inspect(e)) // => the error
}
如果您运行:

Object.getOwnPropertyDescriptors(new Error("message"))
你会得到:

message: {value: "message", writable: true, enumerable: false, configurable: true}
stack: {value: "Error: message↵    at <anonymous>:1:34", writable: true, enumerable: false, configurable: true}
将类似以下内容写入目标文件:

错误:错误
反对。(C:\path\to\file\test.js:3:11)
在模块处编译(Module.js:660:30)
在Object.Module.\u extensions..js(Module.js:671:10)
在Module.load(Module.js:573:32)
在tryModuleLoad时(module.js:513:12)
在Function.Module.\u加载(Module.js:505:3)
位于Function.Module.runMain(Module.js:701:10)
启动时(bootstrap_node.js:193:16)
在bootstrap_node.js:617:3

Yes,错误通常不可
JSON.stringify
able(由于不可枚举属性等原因)。请尝试改用。顺便说一句,
writeFileSync
不接受回调。@普希金我以前从未遇到过在那里放置回调的问题。除非在过去12小时内进行了某种更新,否则这应该没问题。我刚刚在另一个文件中测试了它,它工作得很好。@Bergi谢谢你为我节省了很多以后的打字时间。不过,除了我的手指外,它没有弄断任何东西。@Bergi util.inspect(e)成功了!非常感谢。
const fs = require('fs');
try {
    throw new Error('error');
} catch(error) {
    fs.writeFileSync('err.json', error.stack + '\n', { flag: 'a' });
}