ProgramGuru

Creating Custom Error Classes

Creating Custom Error Classes — the core idea

A custom Error subclass adds domain-specific information such as an error code, making it easier to recover based on error kind. Extend Error, call super(message), and use instanceof when the runtime shares the same class identity.

What you’ll learn

  • Explain creating custom error classes with a concrete use case.
  • Run the example and account for every line of its output.
  • Recognize the difference between compile-time checking and runtime behavior.

Understand the rules and when to use them

Reading the code: The constructor stores field on the instance and delegates message initialization to Error. The thrown object is identified by instanceof, and the error-specific fields are printed.

Keep the boundary clear: Do not treat error message text as a stable programmatic error code. Define a specific property or error subclass when necessary.

See the idea as a flow

Creating Custom Error Classes — conceptual flowError base then ValidationError field then instanceof handlingCreating Custom Error Classes1Error base2ValidationError field3instanceof handlingAsynchronous operations may resume after the current JavaScript stack.
Follow the three stages and identify what happens in TypeScript versus JavaScript.

Run the complete TypeScript example

Save the code as creating-custom-error-classes.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.

TypeScript code

class ValidationError extends Error {
  constructor(readonly field: string, message: string) {
    super(message);
    this.name = "ValidationError";
  }
}
try { throw new ValidationError("email", "invalid value"); }
catch (error: unknown) {
  if (error instanceof ValidationError) console.log(`${error.field}: ${error.message}`);
}

Verified output

email: invalid value

Build: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable creating-custom-error-classes.ts; run: node creating-custom-error-classes.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.

Trace the example line by line

The constructor stores field on the instance and delegates message initialization to Error. The thrown object is identified by instanceof, and the error-specific fields are printed.

The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.

Avoid this common mistake

Do not treat error message text as a stable programmatic error code. Define a specific property or error subclass when necessary.

Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.

Practice independently

Add a code property and catch two different ValidationError instances based on their codes.

Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.

Check your understanding

Why call super(message) in a custom Error class?
Choose one answer. You can try again.

Answer and explanation

To initialize the inherited Error message and base class.

The constructor stores field on the instance and delegates message initialization to Error. The thrown object is identified by instanceof, and the error-specific fields are printed.

What to remember

A custom Error subclass adds domain-specific information such as an error code, making it easier to recover based on error kind.

Try the practice change and re-run the exact program to test your understanding.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Result Types for Error Handling →