11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ci// This test makes sure that when throwing from within a timer's callback,
41cb0ef41Sopenharmony_ci// its active domain at the time of the throw is not the process' active domain
51cb0ef41Sopenharmony_ci// for the next timers that need to be processed on the same turn of the event
61cb0ef41Sopenharmony_ci// loop.
71cb0ef41Sopenharmony_ci
81cb0ef41Sopenharmony_ciconst common = require('../common');
91cb0ef41Sopenharmony_ciconst assert = require('assert');
101cb0ef41Sopenharmony_ciconst domain = require('domain');
111cb0ef41Sopenharmony_ci
121cb0ef41Sopenharmony_ci// Use the same timeout value so that both timers' callbacks are called during
131cb0ef41Sopenharmony_ci// the same invocation of the underlying native timer's callback (listOnTimeout
141cb0ef41Sopenharmony_ci// in lib/timers.js).
151cb0ef41Sopenharmony_cisetTimeout(err, 50);
161cb0ef41Sopenharmony_cisetTimeout(common.mustCall(secondTimer), 50);
171cb0ef41Sopenharmony_ci
181cb0ef41Sopenharmony_cifunction err() {
191cb0ef41Sopenharmony_ci  const d = domain.create();
201cb0ef41Sopenharmony_ci  d.on('error', handleDomainError);
211cb0ef41Sopenharmony_ci  d.run(err2);
221cb0ef41Sopenharmony_ci
231cb0ef41Sopenharmony_ci  function err2() {
241cb0ef41Sopenharmony_ci    // This function doesn't exist, and throws an error as a result.
251cb0ef41Sopenharmony_ci    err3(); // eslint-disable-line no-undef
261cb0ef41Sopenharmony_ci  }
271cb0ef41Sopenharmony_ci
281cb0ef41Sopenharmony_ci  function handleDomainError(e) {
291cb0ef41Sopenharmony_ci    assert.strictEqual(e.domain, d);
301cb0ef41Sopenharmony_ci    // Domains' error handlers are called outside of their domain's context, so
311cb0ef41Sopenharmony_ci    // we're not expecting any active domain here.
321cb0ef41Sopenharmony_ci    assert.strictEqual(process.domain, undefined);
331cb0ef41Sopenharmony_ci  }
341cb0ef41Sopenharmony_ci}
351cb0ef41Sopenharmony_ci
361cb0ef41Sopenharmony_cifunction secondTimer() {
371cb0ef41Sopenharmony_ci  // secondTimer was scheduled before any domain had been created, so its
381cb0ef41Sopenharmony_ci  // callback should not have any active domain set when it runs.
391cb0ef41Sopenharmony_ci  if (process.domain !== null) {
401cb0ef41Sopenharmony_ci    console.log('process.domain should be null in this timer callback, but is:',
411cb0ef41Sopenharmony_ci                process.domain);
421cb0ef41Sopenharmony_ci    // Do not use assert here, as it throws errors and if a domain with an error
431cb0ef41Sopenharmony_ci    // handler is active, then asserting wouldn't make the test fail.
441cb0ef41Sopenharmony_ci    process.exit(1);
451cb0ef41Sopenharmony_ci  }
461cb0ef41Sopenharmony_ci}
47