How do you catch errors in async code?
Inside an async function you use the ordinary try and catch, but you have to await the call inside the try block. A rejected promise only throws when you await it, so a try block that calls the function without awaiting it will not catch anything at all.
async function risky() {
throw new Error('boom');
}
// A promise chain handles the rejection explicitly.
risky()
.then(function () { console.log('not reached'); })
.catch(function (err) { console.log('caught in the chain:', err.message); });
// try and catch works when you await the call.
async function main() {
try {
await risky();
} catch (err) {
console.log('caught with await:', err.message);
}
}
main();There is a subtlety in that snippet that is worth spelling out. The first call is not awaited, but it is not a leak either, because the catch handler is attached to the chain in the same tick. The rule is not that every call must be awaited. The rule is that every promise must end up with a rejection handler somewhere, and there are two ways to do that. You can await the promise inside a try block, or you can attach a catch handler to it.
For code that mixes several operations, a try and catch around a block of awaits is usually the clearest form. If you want to run one step and ignore its failure without stopping the rest, then wrap that step on its own, so that the error is handled exactly where it happens.
One more pattern is worth knowing, and that is the finally method. It runs its callback whatever happened, which makes it the right place for cleanup such as hiding a loading spinner. It does not swallow the error, because it runs before the rejection continues up the chain.