Facebook Pixel

async/await Error Handling Best Practices in JavaScript

try/catch with await is clean but has best practices. Here is how to handle errors well.

async/await Error Handling Best Practices in JavaScript

try/catch with await is the cleanest error handling for async code. Here are the best practices.

1. Always Use try/catch

async function main() { try { const data = await fetch("/api"); render(data); } catch (err) { console.error(err); } }

2. Recover with Fallbacks

async function main() { let data; try { data = await fetch("/api"); } catch { data = fallbackData; } render(data); }

3. Re-throw to Propagate

async function fetchUser(id) { try { const res = await fetch(`/api/${id}`); return res.json(); } catch (err) { console.error("fetchUser failed:", err); throw err; // propagate to caller } }

4. Do Not Swallow Errors

// bad: swallowing try { await fetch("/api"); } catch {} // good: at least log try { await fetch("/api"); } catch (err) { console.error(err); }

5. Use a Helper for Go-style Error Handling

async function to(promise) { try { const data = await promise; return [data, null]; } catch (err) { return [null, err]; } } const [data, err] = await to(fetch("/api")); if (err) handleError(err); else render(data);

The Takeaway

Always use try/catch with await. Recover with fallbacks. Re-throw to propagate. Do not swallow errors. Use a to(promise) helper for Go-style error handling (avoids nested try/catch).

Use try/catch around the await calls. If any await rejects, the catch block runs with the rejection reason. try/catch also catches thrown errors inside the try block.

Assign a fallback value in the catch block, then continue: try { data = await fetch(); } catch { data = fallback; } render(data);. The function continues with the fallback.

Re-throw the error in the catch block: catch (err) { console.error(err); throw err; }. The caller can catch it with their own try/catch.

Yes. catch {} with no logging or handling hides bugs. At minimum, log the error: catch (err) { console.error(err); }. Silent failures make debugging very hard.

Use a to(promise) helper that returns [data, null] or [null, err]. Then: const [data, err] = await to(fetch()); if (err) handleError(err); else render(data);. This is Go-style error handling.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.