[英]Catching errors from spawned Node.js process
Here is an example where child process error
is not fired: 以下是未触发子进程error
的示例:
const spawn = require('child_process').spawn;
const childProcess = spawn('tar', ['--wrong-option'], { stdio: 'inherit' });
childProcess.on('error', err => {
console.error('err: ', err);
});
Why is it so? 为什么会这样? How can the error (error code in particular) be caught from spawned process? 如何从生成的进程中捕获错误(特别是错误代码)?
error
events are only generated when spawning the child itself is causing a problem; 只有在产生孩子本身导致问题时才会生成error
事件; for instance, when the executable doesn't exist. 例如,当可执行文件不存在时。
To catch errors "thrown" by the child process, you should listen for exit
events and check the code
and signal
arguments: 要捕获子进程“抛出”的错误,您应该侦听exit
事件并检查code
和signal
参数:
childProcess.on('exit', (code, signal) => {
if (code) {
console.error('Child exited with code', code)
} else if (signal) {
console.error('Child was killed with signal', signal);
} else {
console.log('Child exited okay');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.