Error Handling
📖 Concept
Error handling prevents your program from crashing when unexpected things happen. JavaScript uses try...catch...finally blocks.
Error types: Error, TypeError, ReferenceError, SyntaxError, RangeError, URIError, EvalError
Custom errors — Extend the Error class for domain-specific errors.
🏠 Real-world analogy: Error handling is like a safety net for trapeze artists. You hope they never fall, but if they do, the net catches them gracefully instead of a crash.
💻 Code Example
1// try...catch...finally2try {3 const data = JSON.parse("invalid json");4} catch (error) {5 console.error("Parse failed:", error.message);6} finally {7 console.log("This ALWAYS runs");8}910// Error properties11try {12 null.property;13} catch (e) {14 console.log(e.name); // "TypeError"15 console.log(e.message); // "Cannot read properties of null"16 console.log(e.stack); // Full stack trace17}1819// Throwing custom errors20function divide(a, b) {21 if (typeof a !== "number" || typeof b !== "number") {22 throw new TypeError("Arguments must be numbers");23 }24 if (b === 0) throw new RangeError("Cannot divide by zero");25 return a / b;26}2728// Custom Error class29class ValidationError extends Error {30 constructor(field, message) {31 super(message);32 this.name = "ValidationError";33 this.field = field;34 }35}36class NotFoundError extends Error {37 constructor(resource) {38 super(`${resource} not found`);39 this.name = "NotFoundError";40 this.statusCode = 404;41 }42}4344// Error handling with specific types45try {46 throw new ValidationError("email", "Invalid email format");47} catch (e) {48 if (e instanceof ValidationError) {49 console.log(`Validation error on ${e.field}: ${e.message}`);50 } else if (e instanceof NotFoundError) {51 console.log(`404: ${e.message}`);52 } else {53 throw e; // Re-throw unknown errors!54 }55}
🏋️ Practice Exercise
Mini Exercise:
- Create a
safeParse(jsonString)function that returns parsed JSON or a default value - Build a
CustomErrorhierarchy for an API:AuthError,NotFoundError,ValidationError - Write middleware that catches and formats errors into a standard response
- Implement retry logic that catches specific errors and retries the operation
⚠️ Common Mistakes
Catching errors and silently ignoring them — at minimum, log the error
Catching ALL errors with a generic catch — only catch errors you can handle; re-throw the rest
Forgetting that
finallyALWAYS runs, even if there's areturnin try or catchThrowing strings instead of Error objects —
throw 'error'loses the stack trace; usethrow new Error('error')Not extending Error properly in custom errors — must call
super(message)first
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Error Handling. Login to unlock this feature.