uncaughtException然后appendFile on error这会导致问题吗?NodeJs

uncaughtException then appendFile on error will this cause problems? NodeJs

本文关键字:问题 NodeJs appendFile 然后 on error uncaughtException      更新时间:2023-09-26

我很好奇,如果因为process.exit(1)是在一个异步的回调操作时,如果发生原始错误的地方将继续运行并处于不稳定状态。我试图将process.exit(1)与fs内联,但它不会写入。

更好的方法来创建一个错误记录,将记录任何错误将受到赞赏。

  const fs = require('fs');
  process.on('uncaughtException', e1 => {
    fs.appendFile('./logs/error.log', e1.stack, e2 => {
      //if (e1 || e2) console.log(e1,e2);
      process.exit(1)
    });
  })

实际上,看起来您的程序每次完成fs.appendFile时都会退出,并向控制台显示一个错误代码。process.exit应该杀死任何其他正在运行的东西,一旦它到达。

我可能会这样做:

const fs = require('fs');
process.on('uncaughtException', function (err) {
  fs.appendFile('./logs/error.log', err.stack, (fserr) => {
    if (err) console.log('FS ERROR', fserr); //now includes the fs error in log
    console.log(err); //maybe include error from uncaughtException?
    process.exit(1); //exit with error code
  });
});