title: How to catch error from a forked child process?
body: <p>Node.js v8.11.1</p>
  
  <p>There are two files: parent.js and child.js. </p>
  
  <p>Parent</p>
  
  <pre><code>const { fork } = require('child_process');
  
  const forked = fork('./child');
  
  forked.on('message', (msg) =&gt; {
    console.log('Message from child', msg);
    forked.kill();
  });
  
  forked.on('error', (err) =&gt; {
    console.log('Error from child', err);
  });
  
  forked.send({ hello: 'world' });
  </code></pre>
  
  <p>Child</p>
  
  <pre><code>process.on('message', (msg) =&gt; {
    console.log('Message from parent:', msg);
  });
  
  try {
    let counter = 0;
  
    seTimeout(() =&gt; {
      process.send({ counter: counter++ });
    }, 1000);
  } catch (err) {
    throw new Error('not good: ' + err);
  }
  </code></pre>
  
  <p>There is an intentional typo in the child script - <code>seTimeout</code>. When I execute parent <code>node parent.js</code>, I get:</p>
  
  <pre><code>/media/trex/safe/Development/child.js:12
    throw new Error('not good: ' + err);
    ^
  
  Error: not good: ReferenceError: seTimeout is not defined
      at Object.&lt;anonymous&gt; (/media/trex/safe/Development/siren/sentinl-private/server/lib/actions/report/child.js:12:9)
      at Module._compile (module.js:652:30)
      at Object.Module._extensions..js (module.js:663:10)
      at Module.load (module.js:565:32)
      at tryModuleLoad (module.js:505:12)
      at Function.Module._load (module.js:497:3)
      at Function.Module.runMain (module.js:693:10)
      at startup (bootstrap_node.js:188:16)
      at bootstrap_node.js:609:3
  </code></pre>
  
  <p>The error was not caught by the parent. How to catch the error by the parent?</p>
  
  <h3>Update 1</h3>
  
  <p>As I see here <a href="https://github.com/nodejs/node/issues/15734" rel="nofollow noreferrer">https://github.com/nodejs/node/issues/15734</a> this is working as intended. Maybe there is another event to catch errors or something else?</p>
  
  <h3>Update 2</h3>
  
  <p>Now I can catch an error the following way. But I'm not sure it is the best way to do it.</p>
  
  <p>Parent</p>
  
  <pre><code>const { fork } = require('child_process');
  
  const forked = fork('./child');
  
  forked.on('message', (msg) =&gt; {
    if (msg.error) {
      console.error(msg.error);
    } else {
      console.log('Message from child', msg);
    }
    forked.kill();
  });
  
  forked.send({ hello: 'world' });
  </code></pre>
  
  <p>Child</p>
  
  <pre><code>process.on('message', (msg) =&gt; {
    console.log('Message from parent:', msg);
  });
  
  try {
    let counter = 0;
  
    seTimeout(() =&gt; {
      process.send({ counter: counter++ });
    }, 1000);
  } catch (err) {
    process.send({error: err.message});
  }
  </code></pre>