Featured
- Get link
- X
- Other Apps
⚠️ Day 38 — Async Error Handling & Try/Catch
⚠️ Day 38 — Async Error Handling & Try/Catch
Hi Guys Welcome to Day 38 🚨 JavaScript is powerful, but errors are inevitable — a server might fail, a network could drop, or invalid data might appear. That’s why learning **error handling** is critical for every real-world developer. Today, we’ll explore try/catch, async error management, and custom error handling.
🧠 1️⃣ What is Error Handling?
Error handling ensures your app continues to work gracefully even when something goes wrong. Without it, one failure could crash your entire script.
try {
let data = JSON.parse('{ name: "Rahul" }'); // ❌ invalid JSON
} catch (err) {
console.log("Something went wrong:", err.message);
}
The try block tests the code; catch handles the error without breaking the app.
🧩 2️⃣ Finally Block
You can use finally to execute code whether an error happens or not — ideal for cleanup operations.
try {
console.log("Starting process...");
throw new Error("Unexpected error occurred!");
} catch (error) {
console.log("Caught:", error.message);
} finally {
console.log("Process ended.");
}
⚙️ 3️⃣ Async Error Handling with Fetch
When using Fetch API, network issues can occur — use try/catch with async/await.
async function getData(){
try {
const res = await fetch("https://jsonplaceholder.typicode.com/invalidURL");
if(!res.ok) throw new Error("Server returned " + res.status);
const data = await res.json();
console.log(data);
} catch (err) {
console.error("Error fetching data:", err.message);
} finally {
console.log("Fetch attempt completed.");
}
}
getData();
💡 4️⃣ Custom Error Throwing
You can create your own errors for specific conditions — helpful for validation.
function validateUser(user) {
if (!user.name) throw new Error("Name is required!");
if (user.age < 18) throw new Error("User must be 18+!");
console.log("User validated successfully.");
}
try {
validateUser({ name: "", age: 16 });
} catch (err) {
console.log("Validation failed:", err.message);
}
🧮 5️⃣ Promise Error Handling
If you’re using Promises instead of async/await, you can handle errors using .catch().
fetch("https://jsonplaceholder.typicode.com/posts/1000")
.then(res => {
if(!res.ok) throw new Error("Resource not found!");
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error("Promise Error:", err.message));
🧠 6️⃣ Real-Life Example: Login Validation
Imagine a login API call — here’s how you’d handle success and failure gracefully.
async function loginUser(email, password) {
try {
if(!email || !password) throw new Error("Please enter all fields!");
const res = await fetch("https://reqres.in/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password })
});
if(!res.ok) throw new Error("Invalid credentials");
const data = await res.json();
console.log("Login successful:", data);
} catch (error) {
console.error("Login failed:", error.message);
}
}
loginUser("test@example.com", "wrongpass");
🎯 Summary
Error handling isn’t about avoiding mistakes — it’s about managing them. Today you learned try/catch/finally, async/await error flow, and how to throw custom exceptions like a professional developer. Tomorrow, you’ll store data permanently using Web Storage APIs — LocalStorage, SessionStorage, and Cookies.
Popular Posts
💙 Day 27: Bootstrap Mini Project – Responsive Portfolio Page
- Get link
- X
- Other Apps
🎨 Day 2: Headings, Paragraphs & Text Formatting
- Get link
- X
- Other Apps
Comments
Post a Comment