错误事件
当 EventEmitter
实例中发生错误时,典型的操作是触发 'error'
事件。
这些在 Node.js 中被视为特殊情况。
如果 EventEmitter
没有为 'error'
事件注册至少一个监听器,并且触发 'error'
事件,则会抛出错误,打印堆栈跟踪,然后退出 Node.js 进程。
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
// 抛出错误并使 Node.js 崩溃
为了防止 Node.js 进程崩溃,可以使用 domain
模块。
(但请注意,不推荐使用 domain
模块。)
作为最佳实践,应始终为 'error'
事件添加监听器。
const myEmitter = new MyEmitter();
myEmitter.on('error', (err) => {
console.error('whoops! there was an error');
});
myEmitter.emit('error', new Error('whoops!'));
// 打印: whoops! there was an error
通过使用符号 errorMonitor
安装监听器,可以在不消费触发的错误的情况下监视 'error'
事件。
const myEmitter = new MyEmitter();
myEmitter.on(EventEmitter.errorMonitor, (err) => {
MyMonitoringTool.log(err);
});
myEmitter.emit('error', new Error('whoops!'));
// 仍然抛出错误并使 Node.js 崩溃
When an error occurs within an EventEmitter
instance, the typical action is
for an 'error'
event to be emitted. These are treated as special cases
within Node.js.
If an EventEmitter
does not have at least one listener registered for the
'error'
event, and an 'error'
event is emitted, the error is thrown, a
stack trace is printed, and the Node.js process exits.
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
// Throws and crashes Node.js
To guard against crashing the Node.js process the domain
module can be
used. (Note, however, that the domain
module is deprecated.)
As a best practice, listeners should always be added for the 'error'
events.
const myEmitter = new MyEmitter();
myEmitter.on('error', (err) => {
console.error('whoops! there was an error');
});
myEmitter.emit('error', new Error('whoops!'));
// Prints: whoops! there was an error
It is possible to monitor 'error'
events without consuming the emitted error
by installing a listener using the symbol errorMonitor
.
const myEmitter = new MyEmitter();
myEmitter.on(EventEmitter.errorMonitor, (err) => {
MyMonitoringTool.log(err);
});
myEmitter.emit('error', new Error('whoops!'));
// Still throws and crashes Node.js