Try/Catch/Finally
// Basic error handling:
try {
const data = JSON.parse("invalid{json"); // throws SyntaxError
processData(data);
} catch (error) {
console.error(error.name, error.message);
} finally {
cleanup(); // always runs
}
// Catching specific errors:
try {
const result = riskyOperation();
} catch (error) {
if (error instanceof TypeError) {
console.error("Type mismatch:", error.message);
} else if (error instanceof RangeError) {
console.error("Out of bounds:", error.message);
} else {
throw error; // re-throw unexpected errors
}
}
// Async error handling:
async function loadData() {
try {
const response = await fetch("/api/data");
if (!response.ok) throw new Error("HTTP " + response.status);
return await response.json();
} catch (error) {
console.error("Load failed:", error.message);
return null;
}
}
Custom Error Classes
class AppError extends Error {
constructor(message, code, statusCode = 500) {
super(message);
this.name = "AppError";
this.code = code;
this.statusCode = statusCode;
}
}
class ValidationError extends AppError {
constructor(message, field) {
super(message, "VALIDATION_ERROR", 400);
this.name = "ValidationError";
this.field = field;
}
}
class NotFoundError extends AppError {
constructor(resource) {
super(resource + " not found", "NOT_FOUND", 404);
this.name = "NotFoundError";
}
}
// Using them:
function validateUser(user) {
if (!user.email) throw new ValidationError("Email required", "email");
if (!user.name) throw new ValidationError("Name required", "name");
}
// Handling:
try {
validateUser({});
} catch (e) {
if (e instanceof ValidationError) {
showFieldError(e.field, e.message);
} else {
throw e;
}
}
⚡ Key Takeaways
- Use instanceof to differentiate error types in catch blocks
- Re-throw errors you can't handle — don't swallow them
- Custom error classes add context (field, statusCode, errorCode)
- Always use finally for cleanup (close connections, hide spinners)
- Global error handlers: window.onerror and process.on('uncaughtException')
🎯 Practice Exercises
EXERCISE 1
Build a custom error hierarchy for a user registration system: ValidationError (with field), DuplicateError, DatabaseError. Write a handler function that shows appropriate UI for each.