Lesson 54 +15 XP

The Error Object

The Error Object

The Error object carries details about an error.

Creating an Error

const err = new Error("Something failed");

Key properties

  • name: the error type, like "Error", "TypeError".
  • message: the description you provided.
  • stack: the stack trace, showing where it happened.
try {
  throw new TypeError("bad input");
} catch (err) {
  console.log(err.name);    // "TypeError"
  console.log(err.message); // "bad input"
  console.log(err.stack);   // trace
}

Built-in error types

  • Error (generic)
  • TypeError (wrong type of value)
  • ReferenceError (missing variable)
  • RangeError (number out of range)
  • SyntaxError (invalid syntax)

Custom error classes

You can build your own error class with a class:

class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}

Why name matters

Checking err.name lets you handle different error types differently.

TL;DR

  • Error has name, message, and stack.
  • Built-in types: Error, TypeError, ReferenceError, RangeError, SyntaxError.
  • You can extend Error to make custom classes.
  • err.name tells you the type.