There is a lot of advice out there that advises you to ensure that you don't let any rejected promises go unhandled. If you don't, the advices cautions, the errors will never be noticed, and will be completely swallowed. Nothing will be printed to the console.
This advice seems to be out-of-date. Modern browsers and modern versions of Node do seem to print warnings when rejected promises are unhandled. Take this code:
async function thisIsGoingToFail() {
await Promise.reject();
console.log('this should not print, as the line above should error');
}
async function main() {
await thisIsGoingToFail();
}
main();
If you run this in Node, you will get:
(node:20760) UnhandledPromiseRejectionWarning: undefined
(node:20760) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:20760) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The standard advice is that the last line in the source code should look like this instead, to avoid swallowed errors:
main().catch(err => { console.err(err) });
But it doesn't look like that like was needed. So here are my questions:
- Is it true that modern browsers and modern Node will always show a warning for unhandled rejected promises? What version numbers of the implementations support this?
- (Note that a browser doesn't have to support the event
unhandledrejectionin order to print a warning when a promise is not handled.)
- (Note that a browser doesn't have to support the event
- Do we need to make sure to have top-level
catchfunctions as you would often get advised to do, or is it just as useful to let the implementation show a warning?