Skip to content
Permalink
Browse files

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 <cjihrig@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information...
addaleax authored and targos committed Aug 3, 2019
1 parent 925e40c commit b7696b41e59ee43dd4031b374636a29d2b887698
@@ -136,7 +136,13 @@ function identicalSequenceRange(a, b) {
}

function enhanceStackTrace(err, own) {
const sep = '\nEmitted \'error\' event at:\n';
let ctorInfo = '';
try {
const { name } = this.constructor;
if (name !== 'EventEmitter')
ctorInfo = ` on ${name} instance`;
} catch {}
const sep = `\nEmitted 'error' event${ctorInfo} at:\n`;

const errStack = err.stack.split('\n').slice(1);
const ownStack = own.stack.split('\n').slice(1);
@@ -170,7 +176,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) {
// eslint-disable-next-line no-restricted-syntax
Error.captureStackTrace(capture, EventEmitter.prototype.emit);
Object.defineProperty(er, kEnhanceStackBeforeInspector, {
value: enhanceStackTrace.bind(null, er, capture),
value: enhanceStackTrace.bind(this, er, capture),
configurable: true
});
} catch {}
@@ -0,0 +1,5 @@
'use strict';
require('../common');
const EventEmitter = require('events');
class Foo extends EventEmitter {}
new Foo().emit('error', new Error());
@@ -0,0 +1,17 @@
events.js:*
throw er; // Unhandled 'error' event
^

Error
at Object.<anonymous> (*events_unhandled_error_subclass.js:*:*)
at Module._compile (internal/modules/cjs/loader.js:*:*)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:*:*)
at Module.load (internal/modules/cjs/loader.js:*:*)
at Function.Module._load (internal/modules/cjs/loader.js:*:*)
at Function.Module.runMain (internal/modules/cjs/loader.js:*:*)
at internal/main/run_main_module.js:*:*
Emitted 'error' event on Foo instance at:
at Object.<anonymous> (*events_unhandled_error_subclass.js:*:*)
at Module._compile (internal/modules/cjs/loader.js:*:*)
[... lines matching original stack trace ...]
at internal/main/run_main_module.js:*:*

0 comments on commit b7696b4

Please sign in to comment.
You can’t perform that action at this time.