Promise Error Handling in JavaScript
😵 Why Handle Errors in Promises?
Promises can either resolve (succeed) or reject (fail). Without error handling, a rejected promise could cause unhandled exceptions and break your app.
>>“Expect the unexpected — always prepare for failure.”
📦 Using catch()
The catch() method is the most common way to handle errors in promise chains.
Basic Error Handling
fetch("https://api.example.com/data")
.then((res) => res.json())
.then((data) => {
console.log("✅ Got data:", data);
})
.catch((error) => {
console.error("❌ Error fetching data:", error);
});Note
💡 catch() will handle any error thrown in the promise chain before it.
🧭 Catching Synchronous Errors
Errors thrown inside then() also get caught by catch().
Code Snippet
Promise.resolve("Start")
.then((val) => {
throw new Error("Something broke!");
})
.catch((err) => {
console.error("Caught:", err.message); // 👉 "Caught: Something broke!"
});🔄 Re-throwing Errors
You can re-throw an error inside catch() if you want to propagate it.
Code Snippet
doSomething()
.catch((err) => {
console.warn("Handled partially");
throw err; // rethrow for further handling
})
.catch((finalErr) => {
console.error("Final handler:", finalErr);
});🧼 Combining with finally()
Use finally() to run cleanup code regardless of success or error.
Code Snippet
getData()
.then(processData)
.catch((err) => console.error("❌ Error:", err))
.finally(() => console.log("🔚 Operation complete"));❌ Unhandled Promise Rejection
If you don’t handle a rejected promise, it causes an unhandled rejection:
Code Snippet
Promise.reject("🔥 Boom!"); // ⚠️ Uncaught (in promise)Note
🚨 Always add catch() to prevent unhandled rejections.
🌐 Global Rejection Handler
In Node.js or modern browsers, you can add a global handler for unhandled rejections:
Browser
window.addEventListener("unhandledrejection", (event) => {
console.warn("Unhandled promise rejection:", event.reason);
});Node.js
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled Rejection:", reason);
});🧠 Summary
- Use .catch() to handle rejected promises and errors.
- Errors thrown inside .then() are also caught by .catch().
- .finally() helps with cleanup after resolution or rejection.
- Always handle rejections to avoid breaking your app.
🔗 References
>>“A good developer doesn't fear rejection — they catch it.”