Skip to content

Instantly share code, notes, and snippets.

@jeremyisatrecharm
Last active December 20, 2022 19:07
Show Gist options
  • Save jeremyisatrecharm/6ec0cc950aa0221334e8af249fef583d to your computer and use it in GitHub Desktop.
Save jeremyisatrecharm/6ec0cc950aa0221334e8af249fef583d to your computer and use it in GitHub Desktop.
Node.js Unhandled Exception
/*
Terminal output:
» node promise-fail.js [13:57:35]
Running test.
- BadPromise running!
- goodPromise running!
error caught
Done with test!
Running test.
- BadPromise running!
/private/tmp/promise-fail.js:11
throw new Error("Failed promise!");
^
Error: Failed promise!
at badPromiseFn (/private/tmp/promise-fail.js:11:9)
at test (/private/tmp/promise-fail.js:24:25)
at /private/tmp/promise-fail.js:6:9
at processTicksAndRejections (node:internal/process/task_queues:96:5)
*/
const run = (async () => {
// Behaves expectedly - error is caught by the catch() after `await Promise.all([...])`.
await test(false);
// Behaves unexpectedly - error is raised BEFORE getting to `await Promise.all([...])`
await test(true);
})();
async function badPromiseFn() {
console.log(" - BadPromise running!");
throw new Error("Failed promise!");
}
async function goodPromiseFn() {
console.log(" - goodPromise running!");
};
async function test(addExtraPromise) {
console.log("Running test.");
// We explicitly DON'T want to await this promise as we want its
// execution to run in the background. BUT, it has an exception internally
// (which should result in a rejected promise).
const failedPromise = badPromiseFn();
// When this is enabled, i.e. there is some work,
if (addExtraPromise) {
await new Promise(function(resolve, reject) {
setTimeout(resolve, 2000);
});
}
try {
await Promise.all([goodPromiseFn(), failedPromise ])
} catch (error) {
console.log("error caught");
} finally {
console.log("Done with test!");
console.log("");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment