Error Handling with Promises in JavaScript

Error Handling with Promises in JavaScript

Error Handling with Promises in JavaScript

Handling errors properly in Promises ensures that issues are caught and handled gracefully without breaking the execution flow.

🔹 Basic Error Handling in Promises

If a Promise rejects, the .catch() method captures the error.

new Promise((resolve, reject) => { setTimeout(() => reject("❌ Something went wrong!"), 2000); }) .then((result) => { console.log("This will never execute", result); }) .catch((error) => { console.log("Caught Error:", error); });

Output (after 2 sec):

Caught Error: ❌ Something went wrong!

Once an error occurs, no further .then() executes.

🔹 Catching Errors Anywhere in the Chain

Errors propagate down the chain until caught by .catch().

new Promise((resolve, reject) => { setTimeout(() => resolve(10), 1000); }) .then((result) => { console.log("Step 1:", result); throw new Error("Something broke!"); }) .then((result) => { console.log("This won't run", result); }) .catch((error) => { console.log("❌ Caught Error:", error.message); });

Output (after 1 sec):

Step 1: 10 ❌ Caught Error: Something broke!

Any error thrown in a .then() jumps to .catch().

🔹 Using .finally() for Cleanup

The .finally() method always executes whether the Promise resolves or rejects.

new Promise((resolve, reject) => { setTimeout(() => reject("Network error!"), 1500); }) .then((result) => console.log("Success:", result)) .catch((error) => console.log("❌ Caught:", error)) .finally(() => console.log("✅ Cleanup completed!"));

Output (after 1.5 sec):

❌ Caught: Network error! ✅ Cleanup completed!

Use .finally() for UI cleanup, logging, etc.

🔹 Handling Errors in async/await

With async/await, use try...catch to handle errors.

async function fetchData() { try { let response = await fetch("https://invalid-url.com"); let data = await response.json(); console.log(data); } catch (error) { console.log("❌ Fetch Error:", error.message); } finally { console.log("✅ Request completed!"); } } fetchData();

Output (if the URL fails to fetch):

Fetch Error: Failed to fetch ✅ Request completed!

Error handling is clearer with try...catch.

🔹 Catching Errors from Multiple Promises

Using Promise.all(), if one fails, the entire Promise.all() fails.

Promise.all([ fetch("https://jsonplaceholder.typicode.com/posts/1").then((res) => res.json()), fetch("https://invalid-url.com").then((res) => res.json()), // Invalid URL ]) .then((data) => console.log("✅ Data:", data)) .catch((error) => console.log("❌ Error in one of the promises:", error.message));

Output (if one request fails):

❌ Error in one of the promises: Failed to fetch

If one request fails, Promise.all() rejects immediately.

🔹 Using Promise.allSettled() to Handle Errors Separately

Unlike Promise.all(), Promise.allSettled() waits for all promises and returns results for both success and failure.

Promise.allSettled([ fetch("https://jsonplaceholder.typicode.com/posts/1").then((res) => res.json()), fetch("https://invalid-url.com").then((res) => res.json()), // Failing request ]) .then((results) => console.log("Results:", results));

Output (success & failure info):

[ { status: "fulfilled", value: { ... } }, { status: "rejected", reason: "Failed to fetch" } ]

Safer when handling multiple requests!

🔹 Summary

.catch() captures errors anywhere in the chain
.finally() runs always (cleanup)
async/await uses try...catch for better readability
Promise.all() fails if one fails
Promise.allSettled() handles both success & failure

🚀 Want more details? Let me know! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close