Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 156 ยท Errors and Debugging

Throwing and Custom Errors

Signal problems from your own code with throw, build custom Error subclasses, wrap low-level failures with cause, and validate input the clean way.

In the previous lesson you caught errors that JavaScript threw for you. Your own code can throw errors too. When a function receives input it can't work with, or reaches a state that should be impossible, the cleanest response is often to stop and say so with the throw statement.

Throwing an error is a way of refusing to continue with bad data. It's much better than quietly returning undefined or NaN and letting the problem surface three functions later, far away from its cause. In this lesson you will throw errors, create your own error classes, chain errors with cause, and use these tools to validate data.

The throw statement

throw takes a value and immediately stops the current function. Control jumps to the nearest catch, exactly as it does for built-in errors:

JS Throwing an error

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Without the check, 10 / 0 would return Infinity, which looks like a number and travels quietly through the rest of your program. The thrown error makes the problem loud and obvious, right where it starts.

Always throw Error objects

JavaScript technically lets you throw anything: throw "oops", throw 404, throw { code: 1 }. Don't. Values that aren't errors have no name, no message and, most importantly, no stack trace, so you lose the information that tells you where the problem came from. Use new Error(...) or one of the built-in types:

JavaScript
throw new TypeError("Expected a string, got " + typeof value);
throw new RangeError("Rating must be between 1 and 5");

Picking a fitting built-in type is a cheap way to give callers extra information. TypeError suits "wrong kind of value", RangeError suits "right kind, but out of bounds".

Rethrowing what you can't handle

A catch block catches everything thrown in its try block, including bugs you didn't expect. A good pattern is to handle the errors you understand and rethrow the rest so they aren't hidden:

JS Handle one kind, rethrow the rest

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The third call has a real bug (a missing property). If the catch block had swallowed every error, that bug would have been disguised as "bad JSON". Rethrowing keeps it visible.

Custom error classes

Built-in types only go so far. In a real application you often want errors that say what part of your program failed: a ValidationError for bad form input, a NotFoundError for a missing record, a PaymentError for a declined card. You create them by extending Error with a class:

JavaScript
class ValidationError extends Error {
  constructor(message, field) {
    super(message);              // sets this.message (and the stack)
    this.name = "ValidationError";
    this.field = field;          // extra information for the caller
  }
}

Three details matter:

  • Call super(message) first, so Error can set up the message and the stack trace.
  • Set this.name. Otherwise the error still calls itself "Error" in the console.
  • Add your own properties. Here, field tells the caller which input was wrong.

Now callers can tell your errors apart with instanceof, the same way they do with built-in types:

JS A custom ValidationError

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The custom error is an Error too, so it works everywhere a normal error does: instanceof Error is true, it has a stack trace, and the console prints it nicely.

A base class for your app

When you have several custom errors, give them a shared parent. Setting the name from new.target.name (or this.constructor.name) saves you from repeating it in every subclass:

JavaScript
class AppError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = new.target.name; // "NotFoundError", "PaymentError", ...
  }
}

class NotFoundError extends AppError {}
class PaymentError extends AppError {}

const error = new NotFoundError("No user with id 42");
console.log(error.name);                  // "NotFoundError"
console.log(error instanceof AppError);   // true

Now a single catch can check instanceof AppError to separate "problems we planned for" from genuine bugs.

Minified code. Build tools that shorten names can also shorten class names, which would change new.target.name. If you ship minified code and rely on error.name, set the name as a fixed string in each class instead.

Wrapping errors with cause

Low-level errors are often too technical to show directly. "Unexpected token < in JSON at position 0" means little to someone reading the logs of a shopping cart. But throwing a new, friendlier error loses the original details.

The cause option solves this. Pass the original error as { cause } when you create the new one, and both are kept:

JS Chaining errors with cause

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The outer error says what the program was trying to do; the cause says why it failed. Developer consoles and Node.js display the cause chain automatically, and logging tools can walk through it. The cause option is part of ES2022 and works in all current browsers and Node.js 16.9+. Custom classes support it too, as long as they pass options on to super() as AppError does above.

Validating input with errors

Throwing is the natural tool for guard clauses at the top of a function: check the input, and refuse early if it's wrong. The body of the function can then assume the data is good.

JS Guard clauses that throw

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When should a function throw, and when should it just return something like null? A useful rule:

  • Return a value when "nothing found" is a normal, expected outcome. array.find() returns undefined, and document.querySelector() returns null: callers check and carry on.
  • Throw when continuing would be a mistake: the caller broke the function's rules, data is corrupt, or something that "can't happen" happened.

Collecting several problems

A form usually has more than one field, and users prefer to see every problem at once. Gather them in an array and throw a single error that holds them all:

JavaScript
class FormError extends Error {
  constructor(problems) {
    super(`${problems.length} field(s) need attention`);
    this.name = "FormError";
    this.problems = problems; // [{ field, message }, ...]
  }
}

The caller catches one FormError and loops over error.problems to mark every invalid field. JavaScript also has a built-in AggregateError for "several errors at once", which Promise.any() uses.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is throw new Error("Out of stock") better than throw "Out of stock"?

    Any value can be thrown, but only Error objects carry the stack trace and the standard properties tools rely on.
  2. 2. In a custom error class, what must the constructor do before using this?

    A subclass constructor must call super() before touching this; passing the message lets Error set it up.
  3. 3. What is the cause option for?

    new Error(msg, { cause: original }) keeps both: what the program was doing, and why it failed.
  4. 4. A catch block only knows how to handle SyntaxError. What should it do with any other error?

    Rethrowing keeps unexpected errors visible instead of disguising real bugs.

Summary

  • throw stops the current function and hands a value to the nearest catch.
  • Always throw Error objects (or built-in subtypes like TypeError and RangeError) so you keep the stack trace.
  • Handle the errors you understand and rethrow the rest.
  • Extend Error to create custom types: call super(message, options), set this.name, add useful properties.
  • Wrap low-level failures with new Error(message, { cause }) to keep the full story.
  • Use throwing guard clauses for invalid input, and plain return values for normal "not found" outcomes.

Next: Debugging Techniques โ€” find bugs faster with breakpoints, the debugger statement and smarter logging.