How to handle errors in async JavaScript functions
· Category: JavaScript
Short answer
Use try/catch blocks around awaited calls, add .catch() to Promise chains, and always validate responses before processing them.
Steps
- Wrap awaited calls in try/catch:
javascript async function load() { try { const res = await fetch("/api/data"); if (!res.ok) throw new Error(res.statusText); return await res.json(); } catch (err) { console.error("Load failed:", err); return null; } } - Catch at the chain level:
javascript fetch("/api/data") .then(r => r.json()) .catch(err => console.error(err)); - Use
.finally()for cleanup regardless of outcome. - Create reusable error boundaries for UI components.
Tips
- Re-throw errors after logging if upstream code needs to handle them.
- Use custom Error subclasses to differentiate error types.
Common issues
- Unhandled Promise rejections may terminate Node.js or clutter browser consoles.
- Catching too early hides errors from higher-level handlers that need context.