1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22'use strict';
23require('../common');
24const assert = require('assert');
25
26const domain = require('domain');
27
28if (process.argv[2] !== 'child') {
29  parent();
30  return;
31}
32
33function parent() {
34  const node = process.execPath;
35  const spawn = require('child_process').spawn;
36  const opt = { stdio: 'inherit' };
37  const child = spawn(node, [__filename, 'child'], opt);
38  child.on('exit', function(c) {
39    assert(!c);
40    console.log('ok');
41  });
42}
43
44let gotDomain1Error = false;
45let gotDomain2Error = false;
46
47let threw1 = false;
48let threw2 = false;
49
50function throw1() {
51  threw1 = true;
52  throw new Error('handled by domain1');
53}
54
55function throw2() {
56  threw2 = true;
57  throw new Error('handled by domain2');
58}
59
60function inner(throw1, throw2) {
61  const domain1 = domain.createDomain();
62
63  domain1.on('error', function(err) {
64    if (gotDomain1Error) {
65      console.error('got domain 1 twice');
66      process.exit(1);
67    }
68    gotDomain1Error = true;
69    throw2();
70  });
71
72  domain1.run(function() {
73    throw1();
74  });
75}
76
77function outer() {
78  const domain2 = domain.createDomain();
79
80  domain2.on('error', function(err) {
81    if (gotDomain2Error) {
82      console.error('got domain 2 twice');
83      process.exit(1);
84    }
85    gotDomain2Error = true;
86  });
87
88  domain2.run(function() {
89    inner(throw1, throw2);
90  });
91}
92
93process.on('exit', function() {
94  assert(gotDomain1Error);
95  assert(gotDomain2Error);
96  assert(threw1);
97  assert(threw2);
98  console.log('ok');
99});
100
101outer();
102