Skip to content
jshacks.dev
Fundamentals

Custom Error Classes in JavaScript and Error Cause

Extend Error to give failures a type, a name and fields, and wrap lower-level errors with cause. See serialization, instanceof checks and AggregateError.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm, Vite, Node.js and TypeScript logos.

A thrown Error("something went wrong") forces every caller to read the message to know what happened, and messages change. A class gives the failure an identity: callers write error instanceof NotFoundError and the code keeps working when the wording is edited. Add a field such as code or field, and handlers can react to data and not text. And the cause option, available since ES2022 and in Node.js 16.9 and later, lets a high-level error wrap the low-level one that triggered it without losing it. This post shows how to write the class, how to wrap with cause, what survives serialization and logging, and when to reach for AggregateError. Output is from Node.js 24 as an ES module. The statements that throw and catch them are in the post on try, catch and finally, and the inheritance syntax is in the post on classes.

A minimal custom error

The class extends Error, passes the message to super and sets a name.

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

const error = new ValidationError("email", "must contain an @");

console.log(error instanceof ValidationError, error instanceof Error);
console.log(error.name, error.field, error.message);
console.log(String(error));
console.log(Object.prototype.toString.call(error));
console.log(typeof error.stack, error.stack.split("\n")[0]);

class Unnamed extends Error {}
console.log(new Unnamed("oops").name);
Text
true true
ValidationError email must contain an @
ValidationError: must contain an @
[object Error]
string ValidationError: must contain an @
Error

The error is an instance of both classes. String(error) uses the name and the message, which is how it shows in many logs. The first line of the stack uses the name, so setting it matters. A subclass that forgets to set name reports itself as Error, as the last line shows, because name is inherited from Error.prototype. A small trick avoids repeating the string: this.name = new.target.name in a base class sets the name to whichever subclass was constructed.

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

class NotFoundError extends AppError {}
class PermissionError extends AppError {}

console.log(new NotFoundError("no row").name, new PermissionError("denied").name);
Text
NotFoundError PermissionError

Branching on type

With classes, handlers branch on the type, and anything unrecognized is rethrown, as described in the error handling post.

JavaScript
class NotFoundError extends Error {
  name = "NotFoundError";
}
class ConflictError extends Error {
  name = "ConflictError";
}

function load(id) {
  if (id === 1) throw new NotFoundError("user 1");
  if (id === 2) throw new ConflictError("duplicate");
  if (id === 3) throw new TypeError("bug in caller");
  return "user " + id;
}

for (const id of [0, 1, 2, 3]) {
  try {
    console.log(load(id));
  } catch (error) {
    if (error instanceof NotFoundError) console.log("404", error.message);
    else if (error instanceof ConflictError) console.log("409", error.message);
    else console.log("unexpected", error.name);
  }
}
Text
user 0
404 user 1
409 duplicate
unexpected TypeError

Each expected failure got its own response, and the TypeError, which signals a bug, fell through to the last branch. Defining name as a class field, as above, is another way to set it. Note that instanceof fails across realms, so errors that cross a frame, worker or vm boundary are better identified by a code string, discussed below.

Wrapping with cause

When a low-level error is caught and a higher-level one is thrown, pass the original as cause. The chain preserves the root problem, which a plain new error would discard.

JavaScript
class DatabaseError extends Error {
  name = "DatabaseError";
}

class UserLoadError extends Error {
  name = "UserLoadError";
  constructor(id, options) {
    super(`could not load user ${id}`, options);
    this.id = id;
  }
}

function query() {
  throw new DatabaseError("connection refused");
}

function loadUser(id) {
  try {
    return query();
  } catch (error) {
    throw new UserLoadError(id, { cause: error });
  }
}

try {
  loadUser(42);
} catch (error) {
  console.log(error.name + ": " + error.message);
  console.log(error.cause.name + ": " + error.cause.message);
  console.log(error.cause instanceof DatabaseError);
  console.log(Object.getOwnPropertyDescriptor(error, "cause").enumerable);
}

function rootCause(error) {
  let current = error;
  while (current?.cause) current = current.cause;
  return current;
}

try {
  loadUser(7);
} catch (error) {
  console.log(rootCause(error).message);
}
Text
UserLoadError: could not load user 42
DatabaseError: connection refused
true
false
connection refused

The outer error says what the caller was trying to do, and the inner one says what failed. The cause property is non-enumerable, so it does not appear in Object.keys(). The rootCause helper walks the chain to the first error with no cause, which is useful for logging and for deciding whether a failure is retryable. Without cause, wrapping loses the original type, and a handler that needed to know the database was down cannot tell.

Codes for stable identification

A string code field is more stable than a class name across package versions, bundlers and realms, and it is what Node.js's own errors use, such as ENOENT and ERR_INVALID_ARG_TYPE.

JavaScript
import { readFile } from "node:fs/promises";

try {
  await readFile("/definitely/not/here.txt");
} catch (error) {
  console.log(error.name, error.code, error.syscall);
  console.log(error instanceof Error);
}

class HttpError extends Error {
  constructor(status, message, options) {
    super(message, options);
    this.name = "HttpError";
    this.status = status;
    this.code = "HTTP_" + status;
  }
}

const notFound = new HttpError(404, "no such route");
console.log(notFound.code, notFound.status);
Text
Error ENOENT open
true
HTTP_404 404

The file system error is a plain Error carrying a code, and code that handles it reads the code and not the class. A custom class can offer both: an instanceof check inside your own code and a code string for consumers who cannot import the class.

Serialization and logging

JSON.stringify(error) surprises people: message and stack are non-enumerable own properties, so the result is almost empty.

JavaScript
const error = new Error("boom", { cause: new Error("root") });
error.code = "E_FAIL";

console.log(JSON.stringify(error));
console.log(Object.keys(error));
console.log(Object.getOwnPropertyNames(error));

class ApiError extends Error {
  constructor(message, details, options) {
    super(message, options);
    this.name = "ApiError";
    this.details = details;
  }

  toJSON() {
    return {
      name: this.name,
      message: this.message,
      details: this.details,
      cause: this.cause?.message,
    };
  }
}

const api = new ApiError("rejected", { field: "email" }, { cause: new Error("db down") });
console.log(JSON.stringify(api));
Text
{"code":"E_FAIL"}
[ 'code' ]
[ 'stack', 'message', 'cause', 'code' ]
{"name":"ApiError","message":"rejected","details":{"field":"email"},"cause":"db down"}

Only the custom code, an own enumerable property, appeared in the first serialization. A toJSON() method returns the fields you want, and keeps the stack out of API responses, where it should not appear. Logging libraries handle errors specially for the same reason, with serializers that extract name, message, stack and the cause chain. Do not return stacks or causes to untrusted clients, since they reveal internals.

AggregateError

AggregateError carries several errors in one, with an errors array. Promise.any() rejects with one when every input fails.

JavaScript
const results = await Promise.any([
  Promise.reject(new Error("first")),
  Promise.reject(new TypeError("second")),
]).catch((error) => error);

console.log(results.name, results.message);
console.log(results.errors.map((e) => e.name + ": " + e.message));
console.log(results instanceof AggregateError);

const combined = new AggregateError(
  [new RangeError("a"), new Error("b")],
  "two checks failed",
);
console.log(combined.errors.length, combined.message);
Text
AggregateError All promises were rejected
[ 'Error: first', 'TypeError: second' ]
true
2 two checks failed

The aggregate holds every individual failure, which is what you want from an operation that tried several things, such as validating a form and reporting all the problems and not only the first. A hand-rolled array of messages works too, and AggregateError standardizes the shape.

Retries and the cause chain

A cause chain is more than a log decoration. A retry policy can walk it to decide whether a failure is worth retrying, so that a timeout at the bottom of three wrappers still triggers a retry while a validation error does not. The decision lives in one helper, and the wrappers stay free of retry logic. Keep the policy conservative: retry only errors you can name, such as a connection reset or a 503, and treat everything else as final. Recording the attempt count on the final error, as a field, makes the logs show how many times the operation was tried before it gave up.

Mapping errors to responses in one place

The payoff of typed errors shows at the edge of an application, where one function turns any thrown error into a response. Handlers deep in the code throw domain errors, and the edge decides the status code, so no handler needs to know about HTTP.

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

class NotFoundError extends AppError {}
class ValidationError extends AppError {
  constructor(field, message) {
    super(message);
    this.field = field;
  }
}

function toResponse(error) {
  if (error instanceof NotFoundError) return { status: 404, body: { error: error.message } };
  if (error instanceof ValidationError) {
    return { status: 422, body: { error: error.message, field: error.field } };
  }
  return { status: 500, body: { error: "internal error" } };
}

const samples = [
  new NotFoundError("order 9 not found"),
  new ValidationError("email", "must contain an @"),
  new TypeError("cannot read properties of undefined"),
];

for (const error of samples) {
  console.log(toResponse(error));
}
Text
{ status: 404, body: { error: 'order 9 not found' } }
{ status: 422, body: { error: 'must contain an @', field: 'email' } }
{ status: 500, body: { error: 'internal error' } }

Known errors produced specific responses, and an unexpected TypeError became a generic 500 with no internal detail, which is what a client should see. The real message goes to the log, with the cause chain, and not to the response. Adding a new kind of failure means one class and one line in this function, and no change to the code that throws it.

Capturing a clean stack

V8 offers Error.captureStackTrace(this, SomeFunction), which omits the constructor frames from the stack so the trace starts where the error was created. It is a V8 feature and not standard JavaScript, and subclass constructors in modern engines already produce a clean enough trace, so most code never needs it. If you build a helper such as assertPositive(n) that throws, passing the helper as the second argument makes the trace point at the caller, which is where the mistake is.

Where custom errors stop paying off

A class for every failure is noise. Start with a base AppError and add subclasses only where a caller would branch on the type. For a small script, a plain Error with a clear message is enough. Do not put sensitive data in messages or fields, because errors travel into logs and sometimes into responses.

If your code is consumed by others, document the code values, since they become part of the contract. Changing a message is not a breaking change, and changing a code is.

Errors are defined in the specification under Error objects, and MDN's pages on Error and its cause property show the options.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.