node/test/parallel/test-timers-reset-process-domain-on-throw.js
Julien Gilli 43a5170858 domain: error handler runs outside of its domain
Before this change, domains' error handlers would run with the
corresponding domain as the active domain. This creates the
possibility for domains' error handlers to call themselves recursively
if an event emitter created in the error handler emits an error, or if
the error handler throws an error.

This change sets the active domain to be the domain's parent (or null
if the domain for which the error handler is called has no parent) to
prevent that from happening.

Fixes: https://github.com/nodejs/node/issues/26086
PR-URL: https://github.com/nodejs/node/pull/26211
Reviewed-By: Vladimir de Turckheim <vlad2t@hotmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Rich Trott <rtrott@gmail.com>
2019-06-12 22:01:07 -07:00

47 lines
1.6 KiB
JavaScript

'use strict';
// This test makes sure that when throwing from within a timer's callback,
// its active domain at the time of the throw is not the process' active domain
// for the next timers that need to be processed on the same turn of the event
// loop.
const common = require('../common');
const assert = require('assert');
const domain = require('domain');
// Use the same timeout value so that both timers' callbacks are called during
// the same invocation of the underlying native timer's callback (listOnTimeout
// in lib/timers.js).
setTimeout(err, 50);
setTimeout(common.mustCall(secondTimer), 50);
function err() {
const d = domain.create();
d.on('error', handleDomainError);
d.run(err2);
function err2() {
// This function doesn't exist, and throws an error as a result.
err3(); // eslint-disable-line no-undef
}
function handleDomainError(e) {
assert.strictEqual(e.domain, d);
// Domains' error handlers are called outside of their domain's context, so
// we're not expecting any active domain here.
assert.strictEqual(process.domain, undefined);
}
}
function secondTimer() {
// secondTimer was scheduled before any domain had been created, so its
// callback should not have any active domain set when it runs.
if (process.domain !== null) {
console.log('process.domain should be null in this timer callback, but is:',
process.domain);
// Do not use assert here, as it throws errors and if a domain with an error
// handler is active, then asserting wouldn't make the test fail.
process.exit(1);
}
}