How to catch an ENOENT with nodejs child_process.spawn?

自古美人都是妖i 提交于 2019-11-28 01:00:49

As with many things in node, child processes can emit an error event. Add a listener for that and you will be able to catch it (no try-catch needed):

var spawn = require('child_process').spawn;
var child = spawn('foo');
child.on('error', function(err) {
  console.log('Oh noez, teh errurz: ' + err);
});

Like mscdex said, you have to attach the 'error' event, however, you should add try catch because some errors, like EPERM doesn't fire the error event and throw Error exception.

var spawn = require('child_process').spawn;
try{
    var child = spawn('foo');
    child.on('error', function(err) {
      console.log('Oh noez, teh errurz: ' + err);
    });
}catch(err){
    console.log("exception: "+err)
}

You can try to catch it with process uncaughtException event. But i believe rest of the task won't be easy though.

process.on('uncaughtException', function (err) {
  console.log(err);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!