Saltar al contenido principal
← ⚡ JavaScript & the browser·Módulo C7 · Lección 2
TareaThrow 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
Teoría

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).

🔒

Regístrate para empezar a programar

La teoría está abierta a todos. El editor, la vista previa y el check se desbloquean con una prueba gratis de 7 días — se requiere tarjeta, cancela cuando quieras.

Registrarse — prueba gratis →

Las primeras 10 lecciones de cada ruta son gratis. No se necesita tarjeta.

← AnteriorSiguiente lección →

Recibe un consejo de Python o web al día — por email

Corto, escrito a mano, sin spam. Anula la suscripción en un clic.