Search code examples
node.jsexceptiontry-catchchild-processspawn

Why does not a try-catch block catch a child_process spawn exception due to invalid executable path in Node.js?


const { spawn } = require("child_process")

try{
    spawn("invalid/path/to/executable")
}catch(err){
    console.log("exception: ",err)
}

This code raises an error and the execution of the program stops. It never prints exception: so the catch block is not executed:

events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: spawn invalid/path/to/executable ENOENT

When run with a valid path to an executable, the same code works.

What can I do to handle the case when the spawn fails due to ENOENT error?


Solution

  • This module fires error event and you can just add a listener for it. You can read more about it here

    So, you can transform your code to:

    const {spawn} = require("child_process")
    
    const subprocess = spawn("invalid/path/to/executable")
    subprocess.on('error', function (err) {
      console.log('Failed to start subprocess: ' + err);
    });
    

    Also, I suggest reading this article by Samer Buna. He covered a lot of interesting topics about this module.