'uncaughtException' 事件


  • err <Error> 未捕获的异常。
  • origin <string> 指示异常是源自未处理的拒绝还是源自同步错误。 可以是 'uncaughtException''unhandledRejection'。 后者仅与设置为 strictthrow--unhandled-rejections 标志和未处理的拒绝结合使用。

当未捕获的 JavaScript 异常一直冒泡回到事件循环时,则会触发 'uncaughtException' 事件。 默认情况下,Node.js 通过将堆栈跟踪打印到 stderr 并以代码 1 退出,覆盖任何先前设置的 process.exitCode 来处理此类异常。 为 'uncaughtException' 事件添加句柄会覆盖此默认行为。 或者,更改 'uncaughtException' 处理程序中的 process.exitCode,这将导致进程以提供的退出码退出。 否则,在存在此类句柄的情况下,进程将以 0 退出。

process.on('uncaughtException', (err, origin) => {
  fs.writeSync(
    process.stderr.fd,
    `Caught exception: ${err}\n` +
    `Exception origin: ${origin}`
  );
});

setTimeout(() => {
  console.log('This will still run.');
}, 500);

// 故意引发异常,但不捕获。
nonexistentFunc();
console.log('This will not run.');

通过安装 'uncaughtExceptionMonitor' 监听器,可以在不覆盖退出进程的默认行为的情况下监视 'uncaughtException' 事件。

  • err <Error> The uncaught exception.
  • origin <string> Indicates if the exception originates from an unhandled rejection or from an synchronous error. Can either be 'uncaughtException' or 'unhandledRejection'. The latter is only used in conjunction with the --unhandled-rejections flag set to strict or throw and an unhandled rejection.

The 'uncaughtException' event is emitted when an uncaught JavaScript exception bubbles all the way back to the event loop. By default, Node.js handles such exceptions by printing the stack trace to stderr and exiting with code 1, overriding any previously set process.exitCode. Adding a handler for the 'uncaughtException' event overrides this default behavior. Alternatively, change the process.exitCode in the 'uncaughtException' handler which will result in the process exiting with the provided exit code. Otherwise, in the presence of such handler the process will exit with 0.

process.on('uncaughtException', (err, origin) => {
  fs.writeSync(
    process.stderr.fd,
    `Caught exception: ${err}\n` +
    `Exception origin: ${origin}`
  );
});

setTimeout(() => {
  console.log('This will still run.');
}, 500);

// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');

It is possible to monitor 'uncaughtException' events without overriding the default behavior to exit the process by installing a 'uncaughtExceptionMonitor' listener.