๐จ Error Handling in Async Code
When working with Promises and async/await
, handling errors properly is crucial to prevent crashes and unexpected behavior.
โ Without Error Handling
async function getData() {
const res = await fetch('https://invalid-url');
const data = await res.json(); // If fetch fails, this will not run
console.log(data);
}
getData();
This will throw a runtime error if the fetch fails.
โ Using try...catch with async/await
async function getData() {
try {
const res = await fetch('https://invalid-url');
if (!res.ok) {
throw new Error('โ Network response was not ok');
}
const data = await res.json();
console.log(data);
} catch (error) {
console.error('๐ฅ Error:', error.message);
} finally {
console.log("โ
Finished trying to fetch data");
}
}
getData();
๐งช Common Scenarios
- Network errors (invalid URLs, server down)
- JSON parsing issues
- Timeouts or unresponsive APIs
- Manually thrown errors inside async blocks
๐ก Tips
- Always wrap async logic inside
try...catch
- Use
finally
for cleanup actions - Check
res.ok
before usingres.json()
- Use error boundaries in UI frameworks like React
๐ก Reminder: Unhandled Promise rejections will crash Node.js apps and be silenced in browsers. Always handle errors!