Skip to content

Commit b7696b4

Browse files
addaleaxtargos
authored andcommitted
events: give subclass name in unhandled 'error' message
For unhandled `'error'` events, include the constructor name for subclasses of EventEmitter, if possible. This makes tracing errors easier when both creation of the `Error` object and emitting it happen in code that does not refer back to the event emitter. PR-URL: #28952 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Rich Trott <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 925e40c commit b7696b4

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

lib/events.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,13 @@ function identicalSequenceRange(a, b) {
136136
}
137137

138138
function enhanceStackTrace(err, own) {
139-
const sep = '\nEmitted \'error\' event at:\n';
139+
let ctorInfo = '';
140+
try {
141+
const { name } = this.constructor;
142+
if (name !== 'EventEmitter')
143+
ctorInfo = ` on ${name} instance`;
144+
} catch {}
145+
const sep = `\nEmitted 'error' event${ctorInfo} at:\n`;
140146

141147
const errStack = err.stack.split('\n').slice(1);
142148
const ownStack = own.stack.split('\n').slice(1);
@@ -170,7 +176,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) {
170176
// eslint-disable-next-line no-restricted-syntax
171177
Error.captureStackTrace(capture, EventEmitter.prototype.emit);
172178
Object.defineProperty(er, kEnhanceStackBeforeInspector, {
173-
value: enhanceStackTrace.bind(null, er, capture),
179+
value: enhanceStackTrace.bind(this, er, capture),
174180
configurable: true
175181
});
176182
} catch {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
'use strict';
2+
require('../common');
3+
const EventEmitter = require('events');
4+
class Foo extends EventEmitter {}
5+
new Foo().emit('error', new Error());
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
events.js:*
2+
throw er; // Unhandled 'error' event
3+
^
4+
5+
Error
6+
at Object.<anonymous> (*events_unhandled_error_subclass.js:*:*)
7+
at Module._compile (internal/modules/cjs/loader.js:*:*)
8+
at Object.Module._extensions..js (internal/modules/cjs/loader.js:*:*)
9+
at Module.load (internal/modules/cjs/loader.js:*:*)
10+
at Function.Module._load (internal/modules/cjs/loader.js:*:*)
11+
at Function.Module.runMain (internal/modules/cjs/loader.js:*:*)
12+
at internal/main/run_main_module.js:*:*
13+
Emitted 'error' event on Foo instance at:
14+
at Object.<anonymous> (*events_unhandled_error_subclass.js:*:*)
15+
at Module._compile (internal/modules/cjs/loader.js:*:*)
16+
[... lines matching original stack trace ...]
17+
at internal/main/run_main_module.js:*:*

0 commit comments

Comments
 (0)