How to create custom error classes in JavaScript

· Category: JavaScript

Short answer

Extending Error lets you create named error types with custom properties, making it easier to distinguish domain-specific failures in catch blocks.

Steps

  1. Define a custom error: javascript class ValidationError extends Error { constructor(message, field) { super(message); this.name = "ValidationError"; this.field = field; } }
  2. Throw and catch it: javascript try { if (!email.includes("@")) { throw new ValidationError("Invalid email", "email"); } } catch (err) { if (err instanceof ValidationError) { console.error(err.field, err.message); } else { throw err; } }
  3. Preserve the stack trace: javascript class ApiError extends Error { constructor(message, status) { super(message); this.name = "ApiError"; this.status = status; Error.captureStackTrace?.(this, ApiError); } }

Tips

  • Always set this.name to the class name for clear stack traces.
  • Re-throw unknown errors instead of swallowing them.

Common issues

  • Forgetting to call super(message) leaves the error message empty.
  • In transpiled code, instanceof may fail across realms or frames.