🟢 EasyError Handling📖 Theory Question

How do you create custom Error types in JavaScript?

💡

Hint

Extend Error class — set this.name, call super(message); enables instanceof checks

Full Answer

class ValidationError extends Error {
  constructor(message, field) {
    super(message);                    // sets .message and .stack
    this.name = 'ValidationError';     // override — default is 'Error'
    this.field = field;                // custom property
  }
}

class NetworkError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.name = 'NetworkError';
    this.statusCode = statusCode;
  }
}

// Usage — instanceof lets you catch specific types
function validate(user) {
  if (!user.name)  throw new ValidationError('Name required',  'name');
  if (!user.email) throw new ValidationError('Email required', 'email');
}

try {
  validate({ name: '' });
} catch (err) {
  if (err instanceof ValidationError) {
    console.log(`Field "${err.field}": ${err.message}`);
  } else if (err instanceof NetworkError) {
    console.log(`HTTP ${err.statusCode}: ${err.message}`);
  } else {
    throw err; // re-throw unknown errors — don't swallow them
  }
}
💡 Always call super(message) — this sets .message and .stack correctly. Always set this.name — otherwise err.name shows 'Error' not 'ValidationError'.

More Error Handling Questions

🟢 EasyHow do you handle errors in async/await properly?→🟢 EasyWhat is error propagation and when should you re-throw an error?→

Practice this in a timed sprint →

5 free questions, no signup required

âš¡ Start Sprint