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
- Define a custom error:
javascript class ValidationError extends Error { constructor(message, field) { super(message); this.name = "ValidationError"; this.field = field; } } - 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; } } - 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.nameto 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,
instanceofmay fail across realms or frames.