'uncaughtExceptionMonitor' 事件


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

'uncaughtExceptionMonitor' 事件在 'uncaughtException' 事件触发或通过 process.setUncaughtExceptionCaptureCallback() 安装的钩子被调用之前触发。

一旦触发 'uncaughtException' 事件,则安装 'uncaughtExceptionMonitor' 监听器不会更改行为。 如果没有安装 'uncaughtException' 监听器,则进程仍然会崩溃。

import process from 'node:process';

process.on('uncaughtExceptionMonitor', (err, origin) => {
  MyMonitoringTool.logSync(err, origin);
});

// 故意引发异常,但不捕获。
nonexistentFunc();
// 仍然崩溃 Node.jsconst process = require('node:process');

process.on('uncaughtExceptionMonitor', (err, origin) => {
  MyMonitoringTool.logSync(err, origin);
});

// 故意引发异常,但不捕获。
nonexistentFunc();
// 仍然崩溃 Node.js
  • err <Error> The uncaught exception.
  • origin <string> Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be 'uncaughtException' or 'unhandledRejection'. The latter is used when an exception happens in a Promise based async context (or if a Promise is rejected) and --unhandled-rejections flag set to strict or throw (which is the default) and the rejection is not handled, or when a rejection happens during the command line entry point's ES module static loading phase.

The 'uncaughtExceptionMonitor' event is emitted before an 'uncaughtException' event is emitted or a hook installed via process.setUncaughtExceptionCaptureCallback() is called.

Installing an 'uncaughtExceptionMonitor' listener does not change the behavior once an 'uncaughtException' event is emitted. The process will still crash if no 'uncaughtException' listener is installed.

import process from 'node:process';

process.on('uncaughtExceptionMonitor', (err, origin) => {
  MyMonitoringTool.logSync(err, origin);
});

// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
// Still crashes Node.jsconst process = require('node:process');

process.on('uncaughtExceptionMonitor', (err, origin) => {
  MyMonitoringTool.logSync(err, origin);
});

// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
// Still crashes Node.js