Error Handling in Async JavaScript (Promises & Async/Await)
When working with asynchronous operations like fetching APIs or reading files, proper error handling is critical to ensure your app doesn't crash and users get meaningful feedback.
Why Handle Errors in Async Code?
- APIs might fail (e.g. 404, 500 errors)
- Network issues may occur
- Your code might throw unexpected exceptions
- Graceful error handling improves user experience
1. Error Handling in Promises
Use .catch() to handle rejected Promises.
fetch("https://jsonplaceholder.typicode.com/invalid-url")
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok!");
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error("Fetch failed:"
, error.message));
Output
Fetch failed: Network response was not ok!
2. Error Handling with async/await + try/catch
Use try/catch blocks to handle errors in async functions.
async function getData() {
try {
const response = await
fetch("https://jsonplaceholder.typicode.com/invalid-url");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log("Data:", data);
} catch (error) {
console.error("Error occurred:", error.message);
}
}
getData();
3. Using finally Block
The finally block runs whether or not there was an error. It’s great for cleanup tasks like hiding a loader or closing a connection.
async function fetchWithLoader() {
console.log(" Loading...");
try {
const res = await
fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await res.json();
console.log(" Data loaded:", data.title);
} catch (err) {
console.error(" Error:", err.message);
} finally {
console.log(" Done loading.");
}
}
fetchWithLoader();
Common Mistakes to Avoid
- Forgetting to check response.ok when using fetch()
- Not returning response.json() properly in chained promises
- Omitting try/catch in async/await blocks