0

I'm running Node.js using VS Code on Windows.

Upon detecting an error condition, how can I completely stop the execution of the script at that point, except for writing a final error message to the console?

I would need to wait until there is a confirmation that the error message has been successfully displayed to the user, and then completely exit the rest of the script without any further execution of the the code past the successful console write?

lifeisfoo
  • 15,478
  • 6
  • 74
  • 115
Richard P
  • 21
  • 5
  • 1
    After your error message is written to the console, you could stop the node process via ’process.exit(1)’. Take a further look at this [post](https://stackoverflow.com/questions/43147330/what-is-difference-between-method-process-exit1-and-process-exit0-in-node-js/47163396). – Martin H. Apr 23 '21 at 21:51

1 Answers1

1

As noted in the nodejs docs, the safe way to exit whitout truncating the outuput is to set the process exitCode and then throw an unhadled exception:

// How to properly set the exit code while letting
// the process exit gracefully.
if (someConditionNotMet()) {
   console.log('final error message');
   process.exitCode = 1;
   throw new Error('Exit'); // must me NOT handled by a try/catch
}

Otherwise, if you want to exit immediately, you can just call process.exit(1), but you cannot be sure that every pending output will be displayed: some text output can be async.

lifeisfoo
  • 15,478
  • 6
  • 74
  • 115