
Product
Announcing Socket Fix 2.0
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
handle-async-await
Advanced tools
You want to use an async function with an error handler. So you use a try-catch
block. But now you cannot assign the return value of this async function to a constant declared outside the try-catch
because of the block scope. And so you are forced to use a variable in lieu of a constant!
let x; // not const
try {
x = await myAsyncFn()
}
catch (error) {
handleError(error);
}
You can always place the try-catch block in a function but this gets tedious and breaks the flow of program logic:
function myAsyncFnWithErrorHandler() {
try {
return await myAsyncFn();
}
catch (error) {
handleError(error);
}
}
const x = await myAsyncFnWithErrorHandler();
Handle Async Await makes it easier to use async functions with error handling.
Install Handle Async Await with your favourite package manager:
<npm|pnpm|yarn> add handle-async-await
In the most general form, users can supply their own error handling function.
import handleAA from 'handle-async-await';
const x = await handleAA(myAsyncFn(), handleError);
If you just wish to augment the error message and throw an error, supply only the string to be appended to the error message as the second argument.
import handleAA from 'handle-async-await';
const x = await handleAA(myAsyncFn(), 'A custom error message');
A space is added when the error message does not end with a whitespace. Bring your own punctuation!
Copyright © 2021, Rahul Gupta.
Handle Async Await is distributed under the terms of the Mozilla Public License, v. 2.0.
FAQs
Graceful Error Handling with Async Await
We found that handle-async-await demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
Security News
Socket CEO Feross Aboukhadijeh joins Risky Business Weekly to unpack recent npm phishing attacks, their limited impact, and the risks if attackers get smarter.
Product
Socket’s new Tier 1 Reachability filters out up to 80% of irrelevant CVEs, so security teams can focus on the vulnerabilities that matter.