Handle async errors with try/catch
A request fails and you want to show a fallback, but the failure happens far from
the line that started it. For synchronous code you already reach for try /
catch; the question is whether that still catches a result that arrives later.
A rejected promise becomes a thrown error at the await. So the natural way
to handle async failure is the same try / catch you already use for
synchronous code:
async function load(id) {
try {
const user = await getUser(id);
return user;
} catch (error) {
return null; // getUser rejected
}
}
When the awaited promise rejects, execution jumps straight from the await to
the catch block, skipping the rest of the try. A finally block runs
afterwards either way, which is the place to release resources:
try {
const data = await fetchData();
return data;
} catch (error) {
return fallback;
} finally {
clearLoader();
}
This is the same failure you would otherwise route through .catch,
written inline instead. If you do not catch it, the error propagates: an async
function that throws returns a rejected promise, and the rejection travels
to whoever awaits it โ or, if nobody does, it becomes an unhandled rejection.
You are about to answer a short quiz on try / catch around await.