Skip to main content
← ⚑ JavaScript & the browserΒ·Module C7 Β· Lesson 3
TaskDefine class NotFoundError extends Error (set this.name). Define class RateLimitError extends Error with extra field retryAfter (number). Throw a NotFoundError('user') in try/catch, log err.name + ': ' + err.message. Throw a RateLimitError(30), log err.name + ': ' + err.retryAfter.

Custom Error classes

125 XP9 min
Theory

When to make your own

Built-in classes (TypeError, RangeError) cover language-level errors. For domain errors β€” "user not found", "rate limited", "stock empty" β€” define your own:

class NotFoundError extends Error {
  constructor(what) {
    super(\`${what} not found\`);
    this.name = "NotFoundError";
  }
}

class RateLimitError extends Error {
  constructor(retryAfter) {
    super(\`rate limited, retry in ${retryAfter}s\`);
    this.name = "RateLimitError";
    this.retryAfter = retryAfter;
  }
}

Why this scales

  • Call sites can if (err instanceof RateLimitError) await sleep(err.retryAfter * 1000).
  • Logging libraries group by err.name.
  • Adding new fields (.userId, .requestId) attaches structured context to the error.

Set this.name in the constructor

If you forget this.name = "...", the error logs as plain "Error: msg" β€” useless for grouping. Always set it.

πŸ”’

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β€” card required, cancel anytime.

Sign up β€” free trial β†’

First 10 lessons in each track are free. No card needed for those.

← PreviousNext lesson β†’

Get one Python or web tip a day β€” by email

Short, hand-written, no spam. Unsubscribe in one click.