🛡️

How to Handle Errors in JavaScript

JavaScriptIntermediate

Try/catch, custom errors, and error handling patterns.

Code Example

JavaScript
// Basic try/catch
try {
  const result = riskyOperation();
  console.log(result);
} catch (error) {
  console.error("Error:", error.message);
}

// Try/catch/finally
try {
  console.log("Trying...");
  throw new Error("Something went wrong");
} catch (error) {
  console.error("Caught:", error.message);
} finally {
  console.log("Always executes");
}

// Custom error classes
class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

function validateAge(age) {
  if (age < 0) {
    throw new ValidationError("age", "Age cannot be negative");
  }
  if (age > 150) {
    throw new ValidationError("age", "Age seems unrealistic");
  }
  return true;
}

try {
  validateAge(-5);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error(`Validation failed for ${error.field}: ${error.message}`);
  } else {
    console.error("Unexpected error:", error);
  }
}

// Error handling in async functions
async function fetchData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    console.error("Fetch failed:", error.message);
    throw error; // Re-throw if needed
  }
}

// Global error handlers
window.addEventListener('error', (event) => {
  console.error('Global error:', event.error);
});

window.addEventListener('unhandledrejection', (event) => {
  console.error('Unhandled promise rejection:', event.reason);
});

// Error boundaries (React pattern)
class ErrorBoundary {
  constructor() {
    this.hasError = false;
  }
  
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  
  componentDidCatch(error, errorInfo) {
    console.error("Error caught:", error, errorInfo);
  }
}

Explanation

Use try/catch for synchronous errors. Custom errors extend Error class. Async errors need try/catch inside async functions. Global handlers catch uncaught errors.

Related Tutorials