2

I have an async function that fails:

async function main() {
    // fails
    throw 'some error';
}

main();

what is the correct way to propagate this exception to end program execution?

Is this:

main().catch(err => { console.log(err); process.exit(1); });

the correct way or is there a better pattern?

Poma
  • 8,174
  • 18
  • 82
  • 144
  • I want this to work as an unhandled exception to halt the program execution. As if `main()` was not async and exception was thrown from it. – Poma Feb 08 '18 at 13:38
  • Doing nothing produces about the same result, doesn't it ? – Denys Séguret Feb 08 '18 at 13:39
  • In that case it prints a warning that unhandled promise rejections are deprecated and program exits with code 0 (success) – Poma Feb 08 '18 at 13:39
  • Then you never handled the rejection, that's what the warning is. You most likely have some other async functions your not returning / waiting on. – Keith Feb 08 '18 at 13:40
  • Actually this function returns a promise and you can handle it in the caller function. if you want to log something in main or produce a new type of exception, you can throw that one. – scetiner Feb 08 '18 at 13:43

1 Answers1

1

There is a better way: You can listen to the "unhandledRejection" event like so :

process.on('unhandledRejection', error => {
     console.log('unhandledRejection', error) //if you want to log the error
     process.exit(1);
});

By doing so, you don't have to catch all your async function that may throw. And you save yourself if there is an error in the catch function.

This will remove the unwanted warning.

Félix Brunet
  • 1,993
  • 1
  • 18
  • 22