According to Node.js documentation usually, it's not a good idea to use process.exit() because async IO operations like console.log() or other logging methods (Pino 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.
I wrote a simplified version of what I currently think is the best option (similar to the solution explained in Node.js docs):
const validateUserInput = (input) => {
  try {
    if (input === 'wrong') { throw new Error('sample error'); } // simplified
  } catch (err) {
    console.log('last message');
    // process.exit(1) --> 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
    
try/catch. Uncaught exceptions will exit (crash) the process by default, and IO that needs to complete (like logging libraries) will hook onto that to handle the crash gracefully.catcherrors and rethrowa different one with a more appropriate message. But still, avoidprocess.exit:-)process.on('uncaughtException')for that. (Same for unhandled promise rejections). Your logging library might even do that for you, see its documentation (getpino.io/#/docs/help?id=exit-logging)