Thuta Learning
JavaScript
IntermediateProgrammingBeginner

Error Types

JavaScriptLesson 2125 min

What you'll walk away with

  • Read an error message and tell which of the four common built-in types it is
  • Use the name, message, stack and cause properties of an Error object
  • Write a custom error class that extends Error with its own name and extra fields
  • Respond differently per error type with instanceof, and tell operational errors from programmer bugs

Explain it simply

Explain it simply

When a patient arrives at a hospital emergency room, "unwell" is not a useful label. Only after deciding whether it is a broken bone, a burn or poisoning can they be sent to the right doctor. Error types are the same kind of label: a single name that says what category of problem occurred.

JavaScript throws a specific type for each situation: ReferenceError when you use a variable that was never declared, TypeError when you read a property of null. For your own app you can create new labels too, such as ValidationError for bad input or NotFoundError when something does not exist.

Problem → Why → Solution

The problem: throwing a string and checking the message crashes inside catch

withdraw() throws the string "Insufficient funds" instead of an Error object. The caller tries to check whether error.message contains "funds", but a string has no message property, so it calls undefined.includes() and a brand-new TypeError is thrown inside the catch block. The code written to handle the error is the code that crashes.

withdraw.js
function withdraw(balance, amount) {
  if (amount > balance) throw "Insufficient funds"; // a string, not an Error
  return balance - amount;
}

try {
  withdraw(100, 500);
} catch (error) {
  if (error.message.includes("funds")) {   // error.message is undefined
    console.log("Please top up your account");
  }
}
// TypeError: Cannot read properties of undefined (reading 'includes')

Why does this happen?

JavaScript lets you throw any value, but only Error objects carry a name, a message and a stack. A thrown string has no stack trace, and callers cannot reliably inspect it. Checking message text is fragile too, because any rewording breaks it. Defining a type such as InsufficientFundsError and checking it with instanceof solves both problems.

Core concept: built-in error types and custom errors

Every Error object has a name (the kind of error), a message (an explanation for humans) and a stack (the chain of function calls that led to it); created with new Error(message, { cause }), it also carries a cause, the original error. Every built-in error type inherits from Error, so error instanceof Error is always true for them.

TypeWhen it appearsExample
SyntaxErrorCode or data is not shaped correctlyJSON.parse("{bad}")
ReferenceErrorA variable name does not existconsole.log(missingName)
TypeErrorA value is used in a way its type does not allownull.toString(), 5()
RangeErrorA number is outside the allowed rangenew Array(-1), (1.5).toFixed(200)

Beyond these four there is URIError, for a malformed URI as in decodeURIComponent("%"), and AggregateError, which bundles many errors, for example when every promise passed to Promise.any() fails. For your app's own domain failures, write a custom class such as class ValidationError extends Error and set this.name in its constructor. Without that, the name "Error" is inherited from Error.prototype and your logs cannot tell the errors apart. You can add useful extra properties such as field or code as well.

Think of errors in two groups. Operational errors, like invalid input or a dropped network connection, are expected problems in a correct program; you handle them by explaining to the user or retrying. Programmer bugs, like a TypeError from reading a property of undefined, mean the code itself is wrong; do not hide them, log them and fix the code. Custom error types make this split easy: anything in your AppError family is operational, and everything else can be treated as a bug.

Mental model: sort the error, then route it
  1. Throw an Error object
  2. In catch, check the type with instanceof
  3. Known type? Handle it
  4. Unknown type? Rethrow it

The message is for humans; the type and code are for your program.

General pattern

javascript
class CustomError extends Error {
  constructor(message, extraInfo, options) {
    super(message, options);     // options may hold { cause }
    this.name = "CustomError";
    this.extraInfo = extraInfo;
  }
}

try { riskyOperation(); } catch (error) {
  if (error instanceof CustomError) handleKnownProblem(error);
  else throw error;
}

super(message, options) hands the message and cause to Error, and this.name is the label shown in logs. In catch, handle only the types you recognise with instanceof and rethrow the rest.

Example: three built-in errors and a ValidationError

Three blocks each trigger one built-in error on purpose and print its name and message. Every message comes from the real error.message, not a hand-written string, so you see exactly what the engine says. Message wording differs between JavaScript engines: this output comes from Node.js (V8), and Firefox words them differently, which is exactly why program logic should check the type, not the message.

error-types.js
// Three built-in error types
function demonstrateErrors() {
  // 1. ReferenceError: a name that was never declared
  try {
    console.log(undefinedVariable);
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }

  // 2. TypeError: using a value in a way its type does not allow
  try {
    null.toString();
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }

  // 3. RangeError: a number outside the allowed range
  try {
    new Array(-1);
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
}

demonstrateErrors();

// A custom error type
class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

function validateAge(age) {
  if (age < 0 || age > 120) {
    throw new ValidationError("Age must be between 0 and 120", "age");
  }
  return `Valid age: ${age}`;
}

try {
  console.log(validateAge(25));
  console.log(validateAge(150));
} catch (error) {
  console.log(`${error.name} (${error.field}): ${error.message}`);
  console.log(error instanceof ValidationError, error instanceof Error);
}

Code breakdown

  1. Line 12null.toString();

    null has no properties at all, so calling a method on it is a TypeError. In practice this is the most common error you will meet, usually when an API response field turns out to be null.

  2. Line 19new Array(-1);

    An array length cannot be negative, so this is a RangeError. The type, a number, is fine; the value is outside the allowed range.

  3. Lines 28-34class ValidationError extends Error {

    Extends Error, passes the message through super(message) and sets this.name explicitly. The extra field property can tell a form which input was wrong.

  4. Line 38throw new ValidationError("Age must be between 0 and 120", "age");

    When the business rule is broken, the function throws a ValidationError rather than a plain Error, so callers can recognise the category.

  5. Line 48console.log(error instanceof ValidationError, error instanceof Error);

    The custom error is an instance of both ValidationError and Error, giving true true. Code that handles "any Error" therefore keeps working with custom errors.

You should see
ReferenceError: undefinedVariable is not defined
TypeError: Cannot read properties of null (reading 'toString')
RangeError: Invalid array length
Valid age: 25
ValidationError (age): Age must be between 0 and 120
true true

A custom error hierarchy with cause

As an app grows, a base class such as AppError is extended by ValidationError, NotFoundError and friends. Writing this.name = this.constructor.name once in the base gives every subclass its own class name automatically, and forwarding options to super() keeps cause working.

app-errors.js
class AppError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = this.constructor.name;
  }
}
class NotFoundError extends AppError {}

const dbError = new Error("connection reset");
const err = new NotFoundError("Order 42 not found", { cause: dbError });
console.log(err.name);          // NotFoundError
console.log(err.cause.message); // connection reset
console.log(err instanceof AppError); // true

In real projects

Where this shows up in real projects

In a REST API server, service code throws custom errors such as ValidationError, NotFoundError and AuthError, and a single error-handling middleware maps them to 400, 404 and 401 with instanceof. An unknown error becomes a 500 with a generic "Something went wrong" for the user, while the full stack trace goes only to the server log, so internal details like database credentials never leak.

On the frontend, form-validation libraries return error objects that include the field name, so each message can appear under the right input. Error-monitoring tools group errors by name, so custom errors with proper names let you see at a glance how many ValidationErrors and how many TypeErrors happened this week. A rising TypeError count is a sign of a programmer bug.

Common mistakes

Common mistakes

1. Forgetting to set this.name in a custom error

With just class DbError extends Error {}, new DbError("timeout").name is "Error" and the log shows only "Error: timeout". instanceof still works, but whoever reads the logs cannot tell which error it was. Set this.name in the constructor, or use this.constructor.name in a base class.

2. Branching on the error message text

A check like if (error.message === "Cannot read properties of null (reading 'toString')") breaks as soon as the wording differs between browsers or Node versions. Rewording your own custom messages should not break logic either. Check instanceof or a stable property such as error.code.

3. Hiding programmer bugs as if they were operational errors

A catch that returns { status: 400, body: "Invalid request" } for every error blames the user even for a TypeError in your own code, and the bug is never noticed. Map only the custom error types you recognise to 4xx responses and log everything else as a 500.

Best practices

Best practices

  • Keep one AppError base class for the whole app and extend it for each domain error.
  • Write error messages for developers, and produce the user-facing text separately.
  • When turning a low-level error into a high-level one, always link the original with { cause }.
  • Throwing a built-in TypeError or RangeError yourself is fine too: for a wrongly typed argument, TypeError says it best.

Mini challenge

Mini challenge: turn errors into HTTP responses

Write an AppError base class with ValidationError and NotFoundError subclasses, plus a toResponse() function that turns any error into an HTTP status and a message that is safe to show users.

  • AppError sets this.name from this.constructor.name and passes options (cause) to super()
  • findUser(id) throws ValidationError for a non-integer id and NotFoundError for any id other than 1
  • toResponse(error) maps ValidationError to 400, NotFoundError to 404 and anything else to 500 with "Something went wrong"
  • Try ids 1, "abc" and 7 plus a TypeError, printing each result
http-errors.js
class AppError extends Error {
  constructor(message, options) {
    // TODO: call super and set this.name from the class name
  }
}
// TODO: ValidationError and NotFoundError, both extending AppError

function findUser(id) {
  // TODO: ValidationError for non-integers, NotFoundError unless id is 1
  // TODO: otherwise return { id, name: "Su Su" }
}

function toResponse(error) {
  // TODO: 400 / 404 for the known types, 500 with a generic body otherwise
}

// TODO: for ids 1, "abc" and 7, print "200 <name>" or "<status> <body>"
// TODO: print the body toResponse gives for a plain TypeError

Expected: The console prints four lines: 200 Su Su 400 Invalid id: abc 404 User 7 not found Something went wrong

Show hint

Number.isInteger("abc") is false. The subclasses need no constructor of their own: they inherit AppError's, and this.constructor.name becomes "ValidationError". In toResponse(), check the specific subclasses with instanceof before anything general.

Show solution
http-errors.js
class AppError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = this.constructor.name;
  }
}
class ValidationError extends AppError {}
class NotFoundError extends AppError {}

function findUser(id) {
  if (!Number.isInteger(id)) throw new ValidationError(`Invalid id: ${id}`);
  if (id !== 1) throw new NotFoundError(`User ${id} not found`);
  return { id, name: "Su Su" };
}

function toResponse(error) {
  if (error instanceof ValidationError) return { status: 400, body: error.message };
  if (error instanceof NotFoundError) return { status: 404, body: error.message };
  return { status: 500, body: "Something went wrong" };
}

for (const id of [1, "abc", 7]) {
  try {
    console.log(200, findUser(id).name);
  } catch (error) {
    const { status, body } = toResponse(error);
    console.log(status, body);
  }
}
console.log(toResponse(new TypeError("x is undefined")).body);

Quick quiz 1 / 3

Which error type does const user = undefined; console.log(user.name); throw?

Quick quiz 2 / 3

What does try { throw "failed"; } catch (error) { console.log(error.stack); } print?

Quick quiz 3 / 3

With only class DbError extends Error {}, what is new DbError("timeout").name?

What to remember

  • Error objects carry name, message, stack (and cause), so throw Errors, never strings.
  • ReferenceError means a missing name, TypeError a wrong type, RangeError an out-of-range value, SyntaxError a malformed shape.
  • For domain failures, extend Error in a custom class and set this.name.
  • In catch, check instanceof or a code rather than message text, and never hide programmer bugs.

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Error Types | Thuta Learning