title: How to catch an ENOENT with nodejs child_process.spawn?
body: <p>I am using <code>spawn</code> to spawn a long running process that sends output over time to stdio, and is read and processed by my nodejs script.  The tricky part is that I cannot guarantee  that the command sent will always be valid.  How can I catch an error in spawning?  Preferably this will not involve installing a global exception handler, since I don't want to handle any other exceptions.  (If that's the only way, I would need to figure out when the spawned process has started up correctly and then uninstall the handler, which is a mess I'd rather not get into.)</p>
  
  <p>The code I want to run would be something like this:</p>
  
  <pre><code>var spawn = require('child_process').spawn;
  
  try {
      spawn("zargle");
  } catch (e) {
      console.error("I'm handling the error!");
  }
  </code></pre>
  
  <p>But this just raises an uncaughtException somewhere in the node event loop, presumably because the call is async and didn't even try to start the child process on my script's time slice.</p>
  
  <p>The only exceptions that need to be caught are when spawn fails to start the process at all (for example, the name is incorrect and ENOENT is thrown).  I am not (at this time) concerned with any problems the spawned process might generate on its own.</p>
  
  <hr>
  
  <p>Similar but different: <a href="https://stackoverflow.com/questions/27688804/how-do-i-debug-error-spawn-enoent-on-node-js">How do I debug &quot;Error: spawn ENOENT&quot; on node.js?</a></p>
  
  <p>I know exactly why I am getting ENOENT, and I know what to change to have the error not happen.  My question is how to gracefully respond to this situation if the error is unavoidable.</p>