title: proper way of handling fatal errors in Node.js
body: <p>According to <a href="https://nodejs.org/api/process.html#process_process_exit_code" rel="noreferrer">Node.js documentation</a> usually, it's not a good idea to use <code>process.exit()</code> because async IO operations like <code>console.log()</code> or other logging methods (<a href="https://getpino.io/" rel="noreferrer">Pino</a> logging library in my case) might get skipped, the process exits before they complete their task. I was wondering what is the best way to handle errors inside a function. My final goal is to handle errors in a function and if the error is a fatal error then exit the process.</p>
  <p>I wrote a simplified version of what I currently think is the best option (similar to the solution explained in Node.js docs):</p>
  <pre><code>const validateUserInput = (input) =&gt; {
    try {
      if (input === 'wrong') { throw new Error('sample error'); } // simplified
    } catch (err) {
      console.log('last message');
      // process.exit(1) --&gt; using this might skip IO operation like the log on previous line
      process.exitCode = 1;
      return false;
    }
    return true;
  };
  
  if (validateUserInput('wrong')) {
    // rest of the code
  }
  
  // nothing should be written here
  </code></pre>