Custom Error Classes in JavaScript
Custom errors (class ValidationError extends Error) categorize failures handlers can distinguish: catch (e) { if (e instanceof ValidationError) ... } routes precisely where message-sniffing guesses. Set name explicitly (this.name = "ValidationError") for readable stacks, pass message to super(), and attach structured context (field, code) as properties.
A small hierarchy (AppError → NotFoundError, AuthError) beats both stringly-typed messages and over-granular class explosions. Libraries export their error classes; consumers catch precisely or let them propagate typed.
Extend Error
class ValidationError extends Error {} — inherits message, stack, and name mechanics freely.
Name and contextualize
this.name = "ValidationError" plus fields (this.field = field) — stacks read correctly, handlers inspect structured data.
Catch by class
instanceof dispatch replaces message parsing — precise routing that survives rewording.
Keep hierarchies shallow
One base plus a handful of leaves covers nearly every app — deep taxonomies complicate without clarifying.
class ValidationError extends Error { constructor(field) { super("bad " + field); this.name = "ValidationError"; this.field = field; }}try { throw new ValidationError("email");} catch (e) { console.log(e.name, e.field);}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.