Skip to content

Commit

Permalink
events: show inspected error in uncaught 'error' message
Browse files Browse the repository at this point in the history
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
  • Loading branch information
addaleax committed Jan 21, 2019
1 parent 30f4568 commit 5babf9d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
12 changes: 10 additions & 2 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,11 @@ EventEmitter.prototype.emit = function emit(type, ...args) {

// If there is no 'error' event listener then throw.
if (doError) {
let er;
let er, stringifiedEr;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
stringifiedEr = er;
try {
const { kExpandStackSymbol } = require('internal/util');
const capture = {};
Expand All @@ -171,10 +172,17 @@ EventEmitter.prototype.emit = function emit(type, ...args) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
} else {
const { inspect } = require('internal/util/inspect');
try {
stringifiedEr = inspect(er);
} catch {
stringifiedEr = er;
}
}
// At least give some kind of context to the user
const errors = lazyErrors();
const err = new errors.ERR_UNHANDLED_ERROR(er);
const err = new errors.ERR_UNHANDLED_ERROR(stringifiedEr);
err.context = er;
throw err; // Unhandled 'error' event
}
Expand Down
17 changes: 15 additions & 2 deletions test/parallel/test-event-emitter-errors.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';
const common = require('../common');
const EventEmitter = require('events');
const util = require('util');

const EE = new EventEmitter();

Expand All @@ -9,7 +10,7 @@ common.expectsError(
{
code: 'ERR_UNHANDLED_ERROR',
type: Error,
message: 'Unhandled error. (Accepts a string)'
message: "Unhandled error. ('Accepts a string')"
}
);

Expand All @@ -18,6 +19,18 @@ common.expectsError(
{
code: 'ERR_UNHANDLED_ERROR',
type: Error,
message: 'Unhandled error. ([object Object])'
message: "Unhandled error. ({ message: 'Error!' })"
}
);

common.expectsError(
() => EE.emit('error', {
message: 'Error!',
[util.inspect.custom]() { throw null; }
}),
{
code: 'ERR_UNHANDLED_ERROR',
type: Error,
message: "Unhandled error. ([object Object])"
}
);

0 comments on commit 5babf9d

Please sign in to comment.