Learn JavaScript
❯ async.async_errors

Async Error Handling in JavaScript

$concept

Async errors demand explicit plumbing: awaited rejections throw into surrounding try/catch, unawaited chains need terminal .catch, and callback APIs need error-first handling — an unhandled rejection crashes modern Node outright. try/catch around await is the primary pattern; .catch chains cover promise style; window unhandledrejection handlers are last-resort telemetry, never logic.

Design rules: reject with Error objects (stacks included), never swallow silently (log or rethrow), separate expected failures (404s as values?) from exceptional ones, and ensure every promise path terminates in handling — floating promises are latent crashes.

$how it works
1

try/catch awaits

try { await risky(); } catch (e) {...} — async throws land in ordinary catch blocks.

2

Terminal .catch chains

promise.then(...).catch(handle) — every floating chain ends in handling, or runtimes complain loudly.

3

Reject with Errors

reject(new Error("...")) carries stacks and types — string rejections debug terribly.

4

Never swallow silently

Empty catches hide failures until production — log, rethrow, or degrade explicitly, always.

$example
async function risky(fail) {
if (fail) throw new Error("boom");
return "fine";
}
async function main() {
try {
console.log(await risky(false));
} catch (e) {
console.log("caught:", e.message);
}
try {
await risky(true);
} catch (e) {
console.log("caught:", e.message);
}
}
main();
Output
fine
caught: boom
1risky(false) fulfills fine — awaited value prints normally.
2risky(true) rejects — the throw lands in catch, printing caught: boom.
3Both paths handled explicitly — success values and failures alike.
$use cases
try/catch around every awaited risky operation
Terminal .catch on promise chains without awaits
Error objects (never strings) for rejections
unhandledrejection telemetry as safety net, not strategy

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.