Aller au contenu principal
← ⚡ JavaScript & the browser·Module C7 · Leçon 2
TâcheThrow a new TypeError('expected number') inside a function and catch it. Log err.name, err.message. Also log err.stack.length > 0 to confirm a stack is present (true/false).

The Error object — name, message, stack

75 XP6 min
Théorie

What's inside an Error

Every Error has three useful fields:

  • err.name — the class name ("Error", "TypeError", "RangeError", custom).
  • err.message — the first arg you passed to new.
  • err.stack — a multi-line string with the call stack at throw time.
const err = new TypeError("expected number");
err.name;     // "TypeError"
err.message;  // "expected number"
err.stack;    // "TypeError: expected number\n    at <anonymous>:1:13..."

Built-in error subclasses

JavaScript ships several subclasses you should reach for instead of bare Error:

  • TypeError — wrong type (e.g. called (undefined).foo).
  • RangeError — number/string outside valid range.
  • SyntaxError — thrown by JSON.parse on bad input.
  • URIError — decodeURIComponent on bad input.

Using the right subclass lets call sites narrow with instanceof (see C7-05).

🔒

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.