Throwing Errors in JavaScript

From the JavaScript cheat sheet · Error Handling · verified Jul 2026

Throwing Errors

Creating and throwing custom errors

javascript
// Throwing errors
throw new Error('Something went wrong');

// Custom error class
class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'ValidationError';
  }
}

throw new ValidationError('Invalid input');
💡 Create custom error classes for specific error types
⚡ Include relevant data in custom errors for better debugging
📌 Error.cause helps chain errors with context
🔥 Always throw Error objects, not strings

More JavaScript tasks

Back to the full JavaScript cheat sheet