2

Say you have a script that looks like

async function main() {
  await somethingThatCanFail()
}

main()

Currently to exit with a non-zero code I'm doing

main()
  .then(() => console.log('success message and stuff')
  .catch(function(err) {
    console.error(err)
    process.exit(1)
  })

because throw new Error(err) is futile inside of a promise. However, this feels kinda hacky, and I'm wondering if there's a more standard way to do this.

m0meni
  • 16,006
  • 16
  • 82
  • 141
  • 1
    `process.exit()` is exactly how you should end your process if you want to end it. Nothing "hacky" about that at all. You fielded an error, decided you wanted to abort the process and ended the process. I would consider an uncaught exception a lot more hacky. – jfriend00 Oct 13 '17 at 14:45
  • 1
    I think this is exactly what you should do, until there's a flag that makes unhandled rejections abort the process. You can already [simulate that](https://stackoverflow.com/a/45771671/1048572), though. – Bergi Oct 13 '17 at 14:45
  • Alright thanks @jfriend00 and Bergi – m0meni Oct 13 '17 at 14:46

1 Answers1

2

process.exit() is exactly how you should end your process if you want to end it. Nothing "hacky" about that at all.

You properly fielded an error, decided you wanted to abort the process because of that error and ended the process in a documented manner. I would consider an uncaught exception a lot more hacky.

You can output to the console anything you want to for diagnostic purposes before exiting if that's what you thought you might be missing from an unhandled exception.

jfriend00
  • 683,504
  • 96
  • 985
  • 979