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?

1
  • 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. Commented Apr 23, 2021 at 21:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.