Skip to content

Commit 9e69cf3

Browse files
committed
process: expose enhanced stack trace to uncaughtException handlers
When an EventEmitter instance emits an unhandled 'error' event, Node attaches an internal stack enhancer (`kEnhanceStackBeforeInspector`) capturing the call site of the `emit('error', ...)` invocation. Previously, `createOnGlobalUncaughtException()` dispatched the error to `uncaughtExceptionMonitor` and `uncaughtException` listeners before applying this enhancement. Consequently, user handlers and monitoring libraries did not see the emitter call site on `err.stack`. This commit enhances the stack trace directly via the internal `kEnhanceStackBeforeInspector` symbol before invoking user handlers, and removes the symbol so the C++ fatal exception exit path does not double-apply the frame if the exception remains unhandled. Also update `test-events-uncaught-exception-stack.js` to assert the enhanced frame is present, and add a comprehensive test suite covering monitor listeners, subclass emitters, and fatal double-call safety. Fixes: nodejs#55838 Signed-off-by: Santusht kotai <[email protected]> Assisted-by: Antigravity
1 parent 8af7545 commit 9e69cf3

3 files changed

Lines changed: 140 additions & 6 deletions

File tree

‎lib/internal/process/execution.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ const {
1717
ERR_INVALID_ARG_TYPE,
1818
ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET,
1919
},
20+
kEnhanceStackBeforeInspector,
2021
} = require('internal/errors');
2122
const { validateFunction } = require('internal/validators');
2223
const { pathToFileURL } = require('internal/url');
@@ -174,6 +175,26 @@ function createOnGlobalUncaughtException() {
174175
// call that threw and was never cleared. So clear it now.
175176
clearDefaultTriggerAsyncId();
176177

178+
// Enhance the stack trace before dispatching to user handlers so that
179+
// both uncaughtExceptionMonitor and uncaughtException listeners receive
180+
// the full stack including the EventEmitter emit call site (e.g.
181+
// "Emitted 'error' event at:"). After enhancing, remove the symbol so
182+
// the C++ ReportFatalException path (which calls
183+
// enhance_fatal_stack_before_inspector) does not apply the same
184+
// enhancement a second time and produce a duplicated stack frame.
185+
if (er != null && typeof er === 'object' &&
186+
typeof er[kEnhanceStackBeforeInspector] === 'function') {
187+
try {
188+
er.stack = er[kEnhanceStackBeforeInspector]();
189+
// The property is configurable:true (set in lib/events.js), so
190+
// deleting it here is safe and prevents a double-enhancement on
191+
// the fatal exit path.
192+
delete er[kEnhanceStackBeforeInspector];
193+
} catch {
194+
// Ignore - enhancing the stack is best-effort.
195+
}
196+
}
197+
177198
const type = fromPromise ? 'unhandledRejection' : 'uncaughtException';
178199
process.emit('uncaughtExceptionMonitor', er, type);
179200
// Primary callback (e.g., domain) has priority and always handles the exception

‎test/parallel/test-events-uncaught-exception-stack.js‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,10 @@ const common = require('../common');
33
const assert = require('assert');
44
const EventEmitter = require('events');
55

6-
// Tests that the error stack where the exception was thrown is *not* appended.
6+
// Tests that the error stack where the exception was emitted is appended.
77

88
process.on('uncaughtException', common.mustCall((err) => {
9-
const [firstLine, ...lines] = err.stack.split('\n');
10-
assert.strictEqual(firstLine, 'Error');
11-
for (const line of lines) {
12-
assert.match(line, /^ {4}at/);
13-
}
9+
assert.match(err.stack, /Emitted 'error' event at:/);
1410
}));
1511

1612
new EventEmitter().emit('error', new Error());
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
'use strict';
2+
// Tests that the enhanced EventEmitter stack trace (containing the
3+
// "Emitted 'error' event at:" frame) is visible to both
4+
// uncaughtExceptionMonitor and uncaughtException handlers.
5+
//
6+
// Also verifies that the enhancement is NOT applied twice on the fatal
7+
// exit path (i.e., no double "Emitted 'error' event at:" frame in crash
8+
// output when there is no handler).
9+
10+
const common = require('../common');
11+
const assert = require('node:assert');
12+
const { spawnSync } = require('node:child_process');
13+
const EventEmitter = require('node:events');
14+
15+
// --- Test 1 & 2: uncaughtExceptionMonitor + uncaughtException ---
16+
// Both handlers must see the enhanced stack before the process would exit.
17+
{
18+
class CustomEmitter extends EventEmitter {}
19+
20+
const ee = new EventEmitter();
21+
const customEE = new CustomEmitter();
22+
23+
let monitorCount = 0;
24+
let handlerCount = 0;
25+
26+
process.on('uncaughtExceptionMonitor', common.mustCall((err, origin) => {
27+
assert.strictEqual(origin, 'uncaughtException');
28+
monitorCount++;
29+
if (monitorCount === 1) {
30+
// Plain EventEmitter - frame must mention the emit call site
31+
assert.match(err.stack, /Emitted 'error' event at:/,
32+
'Monitor: plain EE stack must be enhanced');
33+
assert.match(err.stack, /at emitPlainError/,
34+
'Monitor: plain EE stack must include emitPlainError frame');
35+
} else if (monitorCount === 2) {
36+
// Subclass EventEmitter - frame must include the class name
37+
assert.match(err.stack, /Emitted 'error' event on CustomEmitter instance at:/,
38+
'Monitor: subclass stack must be enhanced with class name');
39+
assert.match(err.stack, /at emitSubclassError/,
40+
'Monitor: subclass stack must include emitSubclassError frame');
41+
}
42+
}, 2));
43+
44+
process.on('uncaughtException', common.mustCall((err, origin) => {
45+
assert.strictEqual(origin, 'uncaughtException');
46+
handlerCount++;
47+
if (handlerCount === 1) {
48+
assert.match(err.stack, /Emitted 'error' event at:/,
49+
'Handler: plain EE stack must be enhanced');
50+
assert.match(err.stack, /at emitPlainError/,
51+
'Handler: plain EE stack must include emitPlainError frame');
52+
// Schedule second throw for next tick after this handler returns
53+
process.nextTick(emitSubclassError);
54+
} else if (handlerCount === 2) {
55+
assert.match(err.stack, /Emitted 'error' event on CustomEmitter instance at:/,
56+
'Handler: subclass stack must be enhanced with class name');
57+
assert.match(err.stack, /at emitSubclassError/,
58+
'Handler: subclass stack must include emitSubclassError frame');
59+
}
60+
}, 2));
61+
62+
function emitPlainError() {
63+
ee.emit('error', new Error('plain error'));
64+
}
65+
66+
function emitSubclassError() {
67+
customEE.emit('error', new Error('subclass error'));
68+
}
69+
70+
emitPlainError();
71+
}
72+
73+
// --- Test 3: No handler - fatal exit path must NOT double-apply the frame ---
74+
// This is the critical regression test: if the C++ ReportFatalException path
75+
// also calls enhance_fatal_stack_before_inspector after we already enhanced,
76+
// the "Emitted 'error' event at:" frame would appear twice in the crash output.
77+
{
78+
const script = `
79+
const EventEmitter = require('node:events');
80+
const ee = new EventEmitter();
81+
function emitError() { ee.emit('error', new Error('crash')); }
82+
emitError();
83+
`;
84+
const result = spawnSync(process.execPath, ['--eval', script], { timeout: 5000 });
85+
86+
// Process must have exited with non-zero due to unhandled error
87+
assert.notStrictEqual(result.status, 0);
88+
89+
const stderr = result.stderr.toString();
90+
91+
// The enhancement must appear - otherwise the fix regressed
92+
assert.match(stderr, /Emitted 'error' event at:/,
93+
'Fatal path: enhanced frame must appear in crash output');
94+
95+
// The enhancement must appear exactly ONCE - the double-call bug would
96+
// cause it to appear twice
97+
const occurrences = (stderr.match(/Emitted 'error' event at:/g) || []).length;
98+
assert.strictEqual(occurrences, 1,
99+
`Fatal path: enhanced frame must appear exactly once, got ${occurrences}`);
100+
}
101+
102+
// --- Test 4: Non-Error EventEmitter emit must not crash ---
103+
// When ee.emit('error', nonError) is called with a non-Error value,
104+
// kEnhanceStackBeforeInspector won't be present on the thrown value.
105+
// The guard (typeof er[kEnhanceStackBeforeInspector] === 'function') must
106+
// prevent any TypeError.
107+
{
108+
process.once('uncaughtException', common.mustCall((err) => {
109+
// Err is a plain object here - no stack enhancement expected
110+
assert.strictEqual(err.message, 'non-error-throw');
111+
}));
112+
113+
process.nextTick(() => {
114+
const thrower = new EventEmitter();
115+
thrower.emit('error', new Error('non-error-throw'));
116+
});
117+
}

0 commit comments

Comments
 (0)