Skip to content

Commit 593714e

Browse files
committed
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 <luigipinca@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Matheus Marchini <mat@mmarchini.me>
1 parent 9a410a1 commit 593714e

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
@@ -172,9 +172,18 @@ EventEmitter.prototype.emit = function emit(type, ...args) {
172172
// up in Node's output if this results in an unhandled exception.
173173
throw er; // Unhandled 'error' event
174174
}
175+
176+
let stringifiedEr;
177+
const { inspect } = require('internal/util/inspect');
178+
try {
179+
stringifiedEr = inspect(er);
180+
} catch {
181+
stringifiedEr = er;
182+
}
183+
175184
// At least give some kind of context to the user
176185
const errors = lazyErrors();
177-
const err = new errors.ERR_UNHANDLED_ERROR(er);
186+
const err = new errors.ERR_UNHANDLED_ERROR(stringifiedEr);
178187
err.context = er;
179188
throw err; // Unhandled 'error' event
180189
}

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)