事件:'uncaughtException'


🌐 Event: 'uncaughtException'

  • err <Error> 未捕获的异常。
  • origin <string> 指示异常是否来源于未处理的拒绝或同步错误。可以是 'uncaughtException''unhandledRejection'。当异常发生在基于 Promise 的异步上下文中(或者如果 Promise 被拒绝)且 --unhandled-rejections 标志设置为 strictthrow(这是默认值)且拒绝未被处理,或者当在命令行入口点的 ES 模块静态加载阶段发生拒绝时,使用后者。

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

🌐 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.

import process from 'node:process';

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.');const process = require('node:process');

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.');

可以通过安装 'uncaughtExceptionMonitor' 监听器来监控 'uncaughtException' 事件,而无需覆盖默认的退出进程行为。

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