javascript - 在 Node.js 中处理 fatal error 的正确方法

标签 javascript node.js error-handling try-catch

根据Node.js documentation通常,使用 process.exit() 不是一个好主意因为像 console.log() 这样的异步 IO 操作或其他日志记录方法(在我的情况下为 Pino 日志库)可能会被跳过,进程在完成任务之前退出。我想知道处理函数内部错误的最佳方法是什么。我的最终目标是处理函数中的错误,如果错误是 fatal error ,则退出该过程。
我写了一个我目前认为是最佳选择的简化版本(类似于 Node.js 文档中解释的解决方案):

const validateUserInput = (input) => {
  try {
    if (input === 'wrong') { throw new Error('sample error'); } // simplified
  } catch (err) {
    console.log('last message');
    // process.exit(1) --> using this might skip IO operation like the log on previous line
    process.exitCode = 1;
    return false;
  }
  return true;
};

if (validateUserInput('wrong')) {
  // rest of the code
}

// nothing should be written here

最佳答案

SIGTERM is the signal that tells a process to gracefully terminate. It is the signal that's sent from process managers like upstart or supervisord and many others.

You can send this signal from inside the program, in another function: read more

process.kill(process.pid, 'SIGTERM')
您还可以为此事件设置自己的监听器,并执行其他任务。
process.on('SIGTERM', () => {
  server.close(() => {
    console.log('Shutting down the application ...')
  })
})
但是SIGTERM windows不支持,所以可以使用SIGINT相反,这里有一个关于 SIGINT 的有用信息

After the SIGINT signal is received, the Node.js server initiates a shutdown sequence and enters shutdown mode. All of the existing requests are completed and no new requests are entertained. When the last request completes, the server closes all of the connections and shuts down. read more


关于流程的更多信息here

关于javascript - 在 Node.js 中处理 fatal error 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70522687/

相关文章:

javascript - 输出PHP时如何转义一个JS变量?

javascript - 自定义上传按钮适用于桌面但不适用于移动设备

javascript - 如何对依赖于 Firebase 引用的函数进行单元测试?

Ruby 脚本引发意外回溯

error-handling - 观星者 lme4 不兼容

Javascript 字符串 match() 方法返回错误 "Uncaught TypeError: Cannot read property ' toString' of null"

javascript - 使用正则表达式替换外部 span-tag

javascript - 在 c++ 和 node.js(服务器)之间建立套接字通信的困难

node.js 模块路径

silverlight - Silverlight错误记录