如何从派生的子进程中捕获错误?

时间:2018-07-26 15:50:24

标签: node.js child-process

Node.js v8.11.1

有两个文件:parent.js和child.js。

父母

const { fork } = require('child_process');

const forked = fork('./child');

forked.on('message', (msg) => {
  console.log('Message from child', msg);
  forked.kill();
});

forked.on('error', (err) => {
  console.log('Error from child', err);
});

forked.send({ hello: 'world' });

孩子

process.on('message', (msg) => {
  console.log('Message from parent:', msg);
});

try {
  let counter = 0;

  seTimeout(() => {
    process.send({ counter: counter++ });
  }, 1000);
} catch (err) {
  throw new Error('not good: ' + err);
}

子脚本中有一个故意的错字-seTimeout。执行父母node parent.js时,我得到:

/media/trex/safe/Development/child.js:12
  throw new Error('not good: ' + err);
  ^

Error: not good: ReferenceError: seTimeout is not defined
    at Object.<anonymous> (/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

该错误未被父级捕获。家长如何发现错误?

更新1

正如我在这里https://github.com/nodejs/node/issues/15734所看到的那样,它正在按预期方式工作。也许还有另一个事件可以捕获错误或其他原因?

更新2

现在,我可以通过以下方式捕获错误。但是我不确定这是最好的方法。

父母

const { fork } = require('child_process');

const forked = fork('./child');

forked.on('message', (msg) => {
  if (msg.error) {
    console.error(msg.error);
  } else {
    console.log('Message from child', msg);
  }
  forked.kill();
});

forked.send({ hello: 'world' });

孩子

process.on('message', (msg) => {
  console.log('Message from parent:', msg);
});

try {
  let counter = 0;

  seTimeout(() => {
    process.send({ counter: counter++ });
  }, 1000);
} catch (err) {
  process.send({error: err.message});
}

1 个答案:

答案 0 :(得分:-1)

为什么不使用option.stdio的数组?此数组具有三个元素[subprocess.stdin, subprocess.stdout, subprocess.stderr],因此您只想控制错误,而不要其他任何操作。

因此,您将使用stdio: ['ignore', 'ignore', 'inherit']

父母

const { execSync } = require('child_process')

try {
  execSync('node myNodeChildScript.js', { stdio: ['ignore', 'ignore', 'inherit'] })
} catch (err) {
  console.error(Error(err))
  process.exit(1)
}

孩子

console.log('Some log') // this will not be output to parent
if (someError()) {
  console.error('There was an error') // this will be output to parent console
  process.exit(1) // exit with error
}