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

codeTap to expand ⛶
1// try...catch...finally
2try {
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}
9
10// Error properties
11try {
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 trace
17}
18
19// Throwing custom errors
20function 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}
27
28// Custom Error class
29class 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}
43
44// Error handling with specific types
45try {
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:

  1. Create a safeParse(jsonString) function that returns parsed JSON or a default value
  2. Build a CustomError hierarchy for an API: AuthError, NotFoundError, ValidationError
  3. Write middleware that catches and formats errors into a standard response
  4. 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 finally ALWAYS runs, even if there's a return in try or catch

  • Throwing strings instead of Error objects — throw 'error' loses the stack trace; use throw 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.