Skip to content

Commit 46a816f

Browse files
addaleaxMylesBorins
authored andcommitted
events: show inspected error in uncaught 'error' message
If there is no handler for `.emit('error', value)` and `value` is not an `Error` object, we currently just call `.toString()` on it. Almost always, using `util.inspect()` provides better information for diagnostic purposes, so prefer to use that instead. Refs: nodejs/help#1729 PR-URL: #25621 Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: Matheus Marchini <[email protected]>
1 parent decba1c commit 46a816f

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

lib/events.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -173,9 +173,18 @@ EventEmitter.prototype.emit = function emit(type, ...args) {
173173
// up in Node's output if this results in an unhandled exception.
174174
throw er; // Unhandled 'error' event
175175
}
176+
177+
let stringifiedEr;
178+
const { inspect } = require('internal/util/inspect');
179+
try {
180+
stringifiedEr = inspect(er);
181+
} catch {
182+
stringifiedEr = er;
183+
}
184+
176185
// At least give some kind of context to the user
177186
const errors = lazyErrors();
178-
const err = new errors.ERR_UNHANDLED_ERROR(er);
187+
const err = new errors.ERR_UNHANDLED_ERROR(stringifiedEr);
179188
err.context = er;
180189
throw err; // Unhandled 'error' event
181190
}

test/parallel/test-event-emitter-errors.js

+14-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
22
const common = require('../common');
33
const EventEmitter = require('events');
4+
const util = require('util');
45

56
const EE = new EventEmitter();
67

@@ -9,12 +10,24 @@ common.expectsError(
910
{
1011
code: 'ERR_UNHANDLED_ERROR',
1112
type: Error,
12-
message: 'Unhandled error. (Accepts a string)'
13+
message: "Unhandled error. ('Accepts a string')"
1314
}
1415
);
1516

1617
common.expectsError(
1718
() => EE.emit('error', { message: 'Error!' }),
19+
{
20+
code: 'ERR_UNHANDLED_ERROR',
21+
type: Error,
22+
message: "Unhandled error. ({ message: 'Error!' })"
23+
}
24+
);
25+
26+
common.expectsError(
27+
() => EE.emit('error', {
28+
message: 'Error!',
29+
[util.inspect.custom]() { throw new Error(); }
30+
}),
1831
{
1932
code: 'ERR_UNHANDLED_ERROR',
2033
type: Error,

0 commit comments

Comments
 (0)