Aller au contenu principal
← ⚡ JavaScript & the browser·Module C7 · Leçon 3
TâcheDefine 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
Théorie

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.

🔒

Inscris-toi pour coder

La théorie est ouverte à tous. L'éditeur, l'aperçu live et le check se débloquent avec un essai gratuit de 7 jours — carte requise, annulable à tout moment.

S'inscrire — essai gratuit →

Les 10 premières leçons de chaque parcours sont gratuites. Pas de carte requise.

← PrécédentLeçon suivante →

Recevez une astuce Python ou web par jour — par email

Court, écrit à la main, sans spam. Désabonnement en un clic.