Learn JavaScript
❯ errors_modules.custom_errors

Custom Error Classes in JavaScript

$concept

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.

$how it works
1

Extend Error

class ValidationError extends Error {} — inherits message, stack, and name mechanics freely.

2

Name and contextualize

this.name = "ValidationError" plus fields (this.field = field) — stacks read correctly, handlers inspect structured data.

3

Catch by class

instanceof dispatch replaces message parsing — precise routing that survives rewording.

4

Keep hierarchies shallow

One base plus a handful of leaves covers nearly every app — deep taxonomies complicate without clarifying.

$example
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);
}
Output
ValidationError email
1The subclass chains message through super and stamps name plus structured field.
2Thrown and caught, it carries class identity (instanceof-able) and data together.
3ValidationError email prints — typed failure with context, no string parsing.
$use cases
Domain error vocabularies (Validation, Auth, NotFound) handlers route on
Library error exports consumers catch precisely
Structured context (fields, codes) alongside messages
Shallow hierarchies over taxonomic excess

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.