JavaScript Me Error Handling Kaise Kare :
JavaScript ek single-threaded language hai jo asynchronous bhi ho sakti hai. Matlab ek samay par ek hi kaam karti hai, lekin events aur promises ke through dusre tasks ko asynchronously manage karti hai.
Is process me errors (galtiyan) aana common hai. Agar inhe properly handle nahi kiya gaya, to program crash ho sakta hai ya security bugs aa sakte hain.
Isi liye Error Handling ka goal hai:
- Program ko stable banana.
- Errors ka clear message dena.
- Application ko crash hone se bachana.
- Debugging aur maintenance ko easy banana.
1. try…catch ka smart use karna
try…catch sabse basic aur powerful tool hai error handling ke liye.
- try block: Jahan risky code rakha jata hai (aisa code jisme error aane ka chance ho).
- catch block: Agar error aata hai to catch block execute hota hai aur hume error ka object milta hai.
try {
let json = '{"name": "Sandeep"}';
let user = JSON.parse(json);
console.log("User name:", user.name);
} catch (error) {
console.error("JSON parse karte waqt error:", error.message);
}
Best Practices:
- Har jagah blindly try…catch mat use karo.
- Sirf wahi code cover karo jisme error ki probability ho (jaise API calls, file reading, JSON parsing, DB queries).
- Agar catch me error mile, to uska proper message log karo.
Common Mistake:
try {
riskyFunction();
} catch (error) {} // kuch bhi handle nahi kiya
Ye galat hai kyunki error ko silently ignore kar diya.
2. Meaningful Error Messages dena :
- Sirf “Error occurred” likhna kabhi helpful nahi hota.
- Developer ko samajhna chahiye ki error kahan hua aur kyun hua.
- User ke liye friendly message dikhana chahiye, technical jargon nahi.
try {
let data = riskyFunction();
} catch (error) {
console.error("riskyFunction fail hua. Reason:", error.message);
}
- Developer logs me detail ho (line number, stack trace).
- User ko readable aur simple message mile. Example: “Server busy, please try again later.”
3. Custom Errors ka use karna :
- Kabhi kabhi hume apni application ke liye custom errors banane hote hain.
- JavaScript me Error class ko extend karke apne errors define kar sakte hain. Ye debugging me madad karta hai.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function checkAge(age) {
if (age < 18) {
throw new ValidationError("Age 18 se kam allowed nahi hai.");
}
return true;
}
try {
checkAge(16);
} catch (error) {
if (error instanceof ValidationError) {
console.error("Validation Error:", error.message);
} else {
console.error("Unknown Error:", error);
}
}
Best Practices:
- Har ek scenario ke liye alag custom error classes banao (jaise AuthError, NetworkError, ValidationError).
- Ye debugging aur logging me alag errors ko identify karne me help karta hai.
4. Graceful Degradation – Program ko crash hone se bachana
- Error handling ka main goal ye hai ki application ruk na jaye.
- Agar ek feature fail hota hai, to baki kaam chalna chahiye.
- Agar data nahi mila to default value dena chahiye.
function getUserData() {
try {
let user = JSON.parse(localStorage.getItem("user"));
return user || { name: "Guest", role: "visitor" };
} catch (error) {
console.warn("User data parse fail hua. Default user return kar rahe hain.");
return { name: "Guest", role: "visitor" };
}
}
Best Practices:
- Fallback mechanism implement karo.
- Default values ya placeholders ka use karo.
- User experience ko smooth banao even if error hota hai.
5. Async/Await aur Promises me Error Handling
Asynchronous code me error handling aur bhi important hai.
a) Promises ke saath .catch():
fetch("https://api.example.com/data")
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.error("API call fail hua:", error.message));
b) Async/Await ke saath try…catch:
async function fetchData() {
try {
let res = await fetch("https://api.example.com/data");
if (!res.ok) throw new Error("Server response not ok");
let data = await res.json();
console.log(data);
} catch (error) {
console.error("Data fetch karte waqt error:", error.message);
}
}
Best Practices:
- Har async call ke around try…catch lagao.
- Agar multiple promises ho to
Promise.allSettled()
use karo taaki ek fail hone par baki continue kare. - Unhandled Promise Rejection ko kabhi ignore mat karo.
6. Global Error Handling
- Aksar kuch errors hote hain jo kisi bhi try…catch ke andar nahi aate.
- Browser me hum window.onerror aur unhandledrejection events ka use kar sakte hain.
window.addEventListener("error", (event) => {
console.error("Global Error Caught:", event.message);
});
window.addEventListener("unhandledrejection", (event) => {
console.error("Unhandled Promise Rejection:", event.reason);
});
Best Practices:
- Global handlers lagao, taki agar kahin bhi error ho to track ho jaye.
- Production me global errors ko logging tool (Sentry, Datadog) me bhejna chahiye.
7. Logging & Monitoring
Console logs development ke liye theek hain, lekin production me ek centralized error tracking system hona chahiye.
Popular tools:
- Sentry
- LogRocket
- Datadog
Ye tools automatically stack trace, user actions aur environment details log karte hain.
Best Practices:
- Production errors ko silently ignore mat karo.
- Error details ko log karo aur monitor karo.
- Agar possible ho to error ke saath timestamp, user ID, aur page info bhi log karo.
8. Never Swallow Errors Silently :
Bohot developers galti karte hain ki error ko catch karke kuch nahi karte.
Wrong:
try {
riskyFunction();
} catch (error) {
// kuch bhi nahi kiya
}
Right:
try {
riskyFunction();
} catch (error) {
console.error("Error caught:", error.message);
}
Best Practices:
- Agar error handle nahi karna to kam se kam usse log karo.
- Silence karne se debugging impossible ho jaati hai.
9. finally block ka use karna (Cleanup ke liye)
finally block hamesha run hota hai – chahe error aaye ya na aaye.
try {
console.log("Processing started...");
throw new Error("Something went wrong!");
} catch (error) {
console.error(error.message);
} finally {
console.log("Cleanup complete – resources released.");
}
Best Practices:
- Database connections, file handles, aur memory cleanup ke liye use karo.
- Async/await ke saath bhi finally useful hai.
Final Conclusion
- try…catch smartly use karo.
- Har jagah meaningful error messages do.
- Custom error classes banao for clarity.
- Graceful degradation aur fallback values use karo.
- Async/await aur Promises me errors hamesha handle karo.
- Global error handlers lagao.
- Logging & monitoring tools (Sentry, LogRocket) ka use karo.
- Errors ko kabhi silently ignore mat karo.
- Cleanup ke liye finally ka use zaroori hai.
Quiz: Test Your Knowledge on Error Handling in JavaScript
Bonus: Practical Application!
Aaj hi JavaScript Error Handling ka use karke apne code ko aur reliable banayein!
JavaScript Error Handling ko sahi tareeke se samajhne ke liye try, catch, finally, throw jaise keywords ka upayog karein. Ye code ko crash hone se bachate hain aur unexpected errors ko handle karne me madad karte hain. Inka use karke aap apne applications ko bug-free, secure aur user-friendly bana sakte hain.