🔍 Error Handling in Async Code (JavaScript)
Handling errors in asynchronous JavaScript is crucial to prevent crashes and ensure
smooth execution. Here are the different ways to handle errors in Promises,
async/await, and Event Loop-based errors.
1️⃣ Handling Errors in Promises (.catch())
When working with Promises, use .catch() to handle errors in asynchronous
operations.
Example:
fetch("https://api.example.com/data")
.then((response) => response.json()) // Parsing JSON
.then((data) => console.log(data)) // Handling data
.catch((error) => console.error("Error:", error)); // Error handling
✅ If fetch() fails (network issue or API error), .catch() will handle it.
2️⃣ Handling Errors with async/await + try...catch
async/await makes code more readable, but we must use try...catch to catch errors.
Example:
async function fetchData() {
try {
let response = await fetch("https://api.example.com/data");
if (!response.ok) throw new Error("Network response was not ok"); // Custom error
handling
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error.message);
fetchData();
✅ Even if the API fails or JSON parsing throws an error, catch will handle it.
3️⃣ Using .catch() with async/await
Another approach is to return a Promise and use .catch() instead of try...catch.
Example:
async function fetchData() {
return fetch("https://api.example.com/data").then((res) => res.json());
fetchData().then(console.log).catch((error) => console.error("Error:", error));
✅ Useful when you want to chain .then() instead of using try...catch.
4️⃣ Handling Multiple Errors with Promise.allSettled()
When dealing with multiple async operations, Promise.all() fails fast (stops at the
first failure).
Instead, Promise.allSettled() ensures all promises complete, whether they succeed or
fail.
Example:
const promises = [
fetch("https://api.example.com/data1").then((res) => res.json()),
fetch("https://api.example.com/data2").then((res) => res.json()),
fetch("https://invalid-url.com").then((res) => res.json()), // Will fail
];
Promise.allSettled(promises).then((results) =>
results.forEach((result) =>
result.status === "fulfilled"
? console.log("Success:", result.value)
: console.error("Error:", result.reason)
);
✅ Ensures all promises complete, and we handle errors separately.
5️⃣ Global Error Handling for Uncaught Errors
Sometimes, errors happen outside of .catch() or try...catch. We can catch them using:
📌 window.onerror (For Browsers)
window.onerror = function (message, source, lineno, colno, error) {
console.error("Global Error Caught:", message);
};
📌 process.on('uncaughtException') (For Node.js)
process.on("uncaughtException", (error) => {
console.error("Uncaught Exception:", error);
});
✅ Catches all unhandled errors and prevents crashes.
6️⃣ Handling Errors in Event Listeners
Errors in event listeners do not crash the app but should still be handled properly.
Example:
document.getElementById("btn").addEventListener("click", () => {
try {
throw new Error("Button Click Error!");
} catch (error) {
console.error("Error in Event Listener:", error.message);
});
✅ Ensures the error is caught without breaking the app.
🔥 Summary: Best Practices for Error Handling
Method Use Case Example
Handle fetch or
.catch() with Promises fetch(url).catch(console.error);
async errors
Handle errors inside
try...catch with async/await try { await fetch(url); } catch (e) {}
async functions
Use .then() instead
.catch() with async/await fetchData().catch(console.error);
of try...catch
Handle multiple
Promise.allSettled() Promise.allSettled(promises).then(...)
async calls safely
window.onerror Catch global errors window.onerror = function (msg) {}
Method Use Case Example
in browsers
process.on('uncaughtExcept Catch global errors process.on("uncaughtException",
ion') in Node.js console.error);
🚀 Conclusion:
Always use .catch() for Promises, try...catch for async/await, and global error
handlers to prevent app crashes. Let me know if you want a visual flowchart of
how error handling works in async code! 🚀