JavaScript Error Handling — Write Bulletproof Code

Master error handling in JavaScript: try/catch, custom errors, error boundaries, debugging techniques, and graceful degradation.

JavaScript Intermediate 📖 8 min

Basic try/catch/finally

try {
  const data = JSON.parse(invalidJSON);
} catch (error) {
  console.error('Parse error:', error.message);
} finally {
  cleanup();
}

Custom Error Classes

class AppError extends Error {
  constructor(message, code, statusCode = 500) {
    super(message);
    this.name = 'AppError';
    this.code = code;
    this.statusCode = statusCode;
    this.isOperational = true;
  }
}

class ValidationError extends AppError {
  constructor(field, message) {
    super(`Validation failed for ${field}: ${message}`, 'VALIDATION_ERROR', 400);
    this.field = field;
  }
}

Error Handling Patterns

// Result pattern (no exceptions)
function divide(a, b) {
  if (b === 0) return { success: false, error: 'Division by zero' };
  return { success: true, data: a / b };
}

// Safe async wrapper
async function safeAsync(fn) {
  try {
    const data = await fn();
    return { data, error: null };
  } catch (error) {
    return { data: null, error };
  }
}

Error Boundaries in React

class ErrorBoundary extends React.Component {
  state = { hasError: false, error: null };
  
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  
  componentDidCatch(error, errorInfo) {
    logErrorToService(error, errorInfo);
  }
  
  render() {
    if (this.state.hasError) {
      return <div>Something went wrong: {this.state.error?.message}</div>;
    }
    return this.props.children;
  }
}

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →