← JS Mastery | Module 6: Async JavaScript Error Handling & Custom Errors
Module 6

Error Handling & Custom Errors

⏱ 18 min read ● Intermediate 🆓 Free

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

🎯 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.

← Fetch API