Skip to content

Instantly share code, notes, and snippets.

@SegersIan
Last active September 21, 2021 06:34
Show Gist options
  • Save SegersIan/bbaaf0c034b943f4a3e2d9cd0524540e to your computer and use it in GitHub Desktop.
Save SegersIan/bbaaf0c034b943f4a3e2d9cd0524540e to your computer and use it in GitHub Desktop.
function thisThrows() {
throw new Error("Thrown from thisThrows()");
}
function myFunctionThatCatches() {
try {
return thisThrows();
} catch (e) {
throw new TypeError(e.message);
} finally {
console.log('We do cleanup here');
}
}
async function run() {
try {
await myFunctionThatCatches();
} catch (e) {
console.error(e);
}
}
run();
// Outputs:
// We do cleanup here
// TypeError: Error: Thrown from thisThrows()
// at myFunctionThatCatches (/repo/error_stacktrace_1.js:9:15) <-- Error points to our try catch block
// at run (/repo/error_stacktrace_1.js:17:15)
// at Object.<anonymous> (/repo/error_stacktrace_1.js:23:1)
@Predarion
Copy link

This misses an await in line 7, should be:
return await thisThrows();

@SegersIan
Copy link
Author

Not really in this case, cause thisThrows() doesn't return promises, nor is myFunctionThatCatches() an async function.

However, I can understand that in a blog post about async/await, an synchronous example might feel out of place/confusing. Given that the entire post is actually about that, I'd might have assumed (based on the other examples) that thisThrows() would return promises and myFunctionThatCatches() would be async.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment