JavaScript Custom Errors: Error Classes, Codes, Causes and AggregateError
A plain Error("Request failed") tells you something went wrong but not what kind of problem it was or what to do about it. Custom error classes fix that: an ApiError can carry the status code and URL, a ValidationError can name the field, and code can decide to retry a TimeoutError but fail fast on a ValidationError. In this lesson you will build custom errors properly, organise them into a small hierarchy, chain causes, collect several errors with AggregateError, and use them to make test failures self-explanatory.
📖 What You’ll Learn: why custom errors help, extending Error correctly, setting name automatically, adding context properties and error codes, checking errors with instanceof and codes, error hierarchies, cause chains and printing them, AggregateError for multiple failures, serialising errors for logs and reports, result objects as an alternative, and a retry decision based on error types.
🤔 Why Create Custom Errors?
Compare what the caller can do with a generic error versus a custom one:
📄 why.js
class ApiError extends Error {
constructor(message, { status, url } = {}) {
super(message);
this.name = "ApiError";
this.status = status;
this.url = url;
}
}
const generic = new Error("Request failed");
const custom = new ApiError("Request failed", { status: 503, url: "/api/orders" });
console.log(generic.name, "|", generic.message);
console.log(custom.name, "|", custom.message, "|", custom.status, custom.url);
console.log("retry?", custom instanceof ApiError && custom.status >= 500);
⌨️ Terminal
node why.js
🖥️ Output
Error | Request failed
ApiError | Request failed | 503 /api/orders
retry? true
- Type:
instanceof ApiErrorlets code handle API problems differently from bugs. - Context: status and URL travel with the error to wherever it is caught or logged.
- Decisions: callers can retry server errors (5xx) but not client errors (4xx).
🏗️ Extending Error Correctly
Definition: a custom error is a class that extends Error (or one of its subclasses). Three rules make it behave like a built-in error:
- Call
super(message, options)first, somessage,stackandcauseare set. - Set
this.nameso the type appears in logs and stack traces. Usingnew.target.nameorthis.constructor.namesets it automatically for every subclass. - Add only the extra properties callers need.
📄 extend.js
class AppError extends Error {
constructor(message, options) {
super(message, options); // options may contain { cause }
this.name = new.target.name; // "AppError", or the subclass name
}
}
class ConfigError extends AppError {}
const e = new ConfigError("BASE_URL is not set");
console.log(e.name, "|", e.message);
console.log(e instanceof ConfigError, e instanceof AppError, e instanceof Error);
console.log(e.stack.split("\n")[0]);
console.log(String(e));
⌨️ Terminal
node extend.js
🖥️ Output
ConfigError | BASE_URL is not set
true true true
ConfigError: BASE_URL is not set
ConfigError: BASE_URL is not set
⚠️ Watch out: If you forget this.name, the error prints as a plain Error in stack traces and logs, which hides its type. Setting it once in a base class with new.target.name covers every subclass.
🏷️ Context Properties and Error Codes
Messages are for humans; error codes are for code. Node.js itself uses codes such as ENOENT and ERR_ASSERTION. Codes stay stable when messages are reworded, so checks based on them do not break.
📄 codes.js
class ValidationError extends Error {
constructor(field, problem, value) {
super(`${field}: ${problem} (got ${JSON.stringify(value)})`);
this.name = "ValidationError";
this.code = "E_VALIDATION";
this.field = field;
this.value = value;
}
}
function validateUser(user) {
if (!user.email?.includes("@")) throw new ValidationError("email", "must contain @", user.email);
if (!(user.age >= 18)) throw new ValidationError("age", "must be 18 or older", user.age);
return true;
}
for (const user of [{ email: "asha@sqatools.in", age: 29 }, { email: "asha", age: 29 }, { email: "a@b.in", age: 15 }]) {
try {
console.log("valid:", validateUser(user));
} catch (e) {
if (e.code === "E_VALIDATION") console.log(`invalid field "${e.field}" -> ${e.message}`);
else throw e;
}
}
const fs = require("node:fs");
try {
fs.readFileSync("missing-file.json");
} catch (e) {
console.log("Node.js error code:", e.code);
}
⌨️ Terminal
node codes.js
🖥️ Output
valid: true
invalid field "email" -> email: must contain @ (got "asha")
invalid field "age" -> age: must be 18 or older (got 15)
Node.js error code: ENOENT
🌳 A Small Error Hierarchy
Group related errors under a common base so callers can catch broadly or narrowly. Keep it shallow: two levels are usually enough.
📄 hierarchy.js
class AppError extends Error {
constructor(message, options) { super(message, options); this.name = new.target.name; }
}
class HttpError extends AppError {
constructor(status, url, options) {
super(`HTTP ${status} for ${url}`, options);
this.status = status;
this.url = url;
}
get retryable() { return this.status >= 500 || this.status === 429; }
}
class NotFoundError extends HttpError {
constructor(url) { super(404, url); }
}
class TimeoutError extends AppError {
constructor(ms, url) { super(`Timed out after ${ms} ms: ${url}`); this.retryable = true; }
}
const errors = [new NotFoundError("/api/users/99"), new HttpError(503, "/api/orders"), new TimeoutError(5000, "/api/search"), new TypeError("x is not a function")];
for (const e of errors) {
const kind = e instanceof NotFoundError ? "not found"
: e instanceof HttpError ? "http error"
: e instanceof AppError ? "app error"
: "unexpected bug";
console.log(`${e.name.padEnd(13)} ${kind.padEnd(14)} retryable=${e.retryable ?? false}`);
}
⌨️ Terminal
node hierarchy.js
🖥️ Output
NotFoundError not found retryable=false
HttpError http error retryable=true
TimeoutError app error retryable=true
TypeError unexpected bug retryable=false
💡 Tip: Check the most specific class first. NotFoundError is also an HttpError and an AppError, so the order of instanceof checks matters.
🔗 Cause Chains
Each layer of a program can add context by wrapping the error it caught, passing the original as cause. The result is a chain from the high-level problem down to the root cause:
📄 cause-chain.js
class AppError extends Error {
constructor(message, options) { super(message, options); this.name = new.target.name; }
}
function readRow() {
return JSON.parse("{'id': 1}"); // low level: SyntaxError
}
function loadUsers() {
try { return readRow(); }
catch (e) { throw new AppError("Could not parse users.csv row 3", { cause: e }); }
}
function setupTest() {
try { return loadUsers(); }
catch (e) { throw new AppError("Test data setup failed for checkout.spec", { cause: e }); }
}
function printChain(error) {
let depth = 0;
for (let e = error; e; e = e.cause) {
console.log(`${" ".repeat(depth++)}${depth > 1 ? "caused by " : ""}${e.name}: ${e.message}`);
}
}
try {
setupTest();
} catch (e) {
printChain(e);
}
⌨️ Terminal
node cause-chain.js
🖥️ Output
AppError: Test data setup failed for checkout.spec
caused by AppError: Could not parse users.csv row 3
caused by SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
Node.js also prints the cause chain automatically when such an error is uncaught.
📦 AggregateError: Several Errors at Once
Definition: AggregateError is a built-in error that holds an array of errors in its errors property. Promise.any throws it when every promise fails, and you can throw it yourself when a validation or a batch produces several failures:
📄 aggregate.js
function validateForm(form) {
const problems = [];
if (!form.name) problems.push(new Error("name is required"));
if (!/^\d{6}$/.test(form.pin ?? "")) problems.push(new Error("pin must be 6 digits"));
if (!form.terms) problems.push(new Error("terms must be accepted"));
if (problems.length) throw new AggregateError(problems, `${problems.length} field(s) invalid`);
return true;
}
try {
validateForm({ name: "", pin: "41100" });
} catch (e) {
console.log(e.name, "-", e.message);
e.errors.forEach((err, i) => console.log(` ${i + 1}. ${err.message}`));
}
Promise.any([Promise.reject(new Error("mirror 1 down")), Promise.reject(new Error("mirror 2 down"))])
.catch((e) => console.log(e.constructor.name, e.errors.map((x) => x.message)));
⌨️ Terminal
node aggregate.js
🖥️ Output
AggregateError - 3 field(s) invalid
1. name is required
2. pin must be 6 digits
3. terms must be accepted
AggregateError [ 'mirror 1 down', 'mirror 2 down' ]
Reporting every problem at once (“3 fields invalid”) is much friendlier than failing on the first one and making someone fix and rerun three times.
📝 Serialising Errors for Logs and Reports
JSON.stringify(error) returns {} for errors, because message and stack are not enumerable own properties. Add a toJSON() method, or convert errors explicitly before writing them to a JSON report:
📄 serialize.js
console.log(JSON.stringify(new Error("boom")));
class ApiError extends Error {
constructor(message, { status, url } = {}) {
super(message);
this.name = "ApiError";
this.status = status;
this.url = url;
}
toJSON() {
return { name: this.name, message: this.message, status: this.status, url: this.url };
}
}
console.log(JSON.stringify(new ApiError("Service unavailable", { status: 503, url: "/api/pay" })));
const toPlain = (e) => ({ name: e.name, message: e.message, ...(e.cause && { cause: toPlain(e.cause) }) });
console.log(JSON.stringify(toPlain(new Error("outer", { cause: new TypeError("inner") }))));
⌨️ Terminal
node serialize.js
🖥️ Output
{}
{"name":"ApiError","message":"Service unavailable","status":503,"url":"/api/pay"}
{"name":"Error","message":"outer","cause":{"name":"TypeError","message":"inner"}}
⚠️ Watch out: Before logging an error’s context, make sure it contains no secrets. Request headers, tokens and passwords stored on an error object end up in CI logs and reports.
⚖️ Throwing vs Returning a Result
Exceptions are for situations the current code cannot handle. When a failure is an expected, normal outcome (a search with no results, an optional file), returning a result object can be clearer than throwing:
📄 result.js
function findUser(users, email) {
const user = users.find((u) => u.email === email);
return user ? { ok: true, user } : { ok: false, reason: `no user with email ${email}` };
}
const users = [{ email: "asha@sqatools.in", name: "Asha" }];
for (const email of ["asha@sqatools.in", "ghost@sqatools.in"]) {
const result = findUser(users, email);
console.log(result.ok ? `found ${result.user.name}` : result.reason);
}
⌨️ Terminal
node result.js
🖥️ Output
found Asha
no user with email ghost@sqatools.in
| Throw an error when… | Return a result when… |
|---|---|
| The caller cannot continue (bad config, broken API, failed assertion) | Failure is a normal, expected case |
| The problem must not be ignored | The caller will always check the outcome |
| You want a stack trace | Performance matters in a hot loop |
🧪 Tester Scenario: Retry Only What Is Worth Retrying
This API helper throws typed errors, and a retry wrapper uses those types to decide: retry timeouts and 5xx responses, fail immediately on 4xx and on bugs. Every failure keeps its full context for the report.
📄 retry.js
class AppError extends Error {
constructor(message, options) { super(message, options); this.name = new.target.name; }
}
class HttpError extends AppError {
constructor(status, url) { super(`HTTP ${status} for ${url}`); this.status = status; this.url = url; }
get retryable() { return this.status >= 500; }
}
class TimeoutError extends AppError {
retryable = true;
}
// Simulated server: answers differ per attempt
const scripted = { "/api/orders": [new TimeoutError("timeout 5000 ms"), new HttpError(503, "/api/orders"), { items: 3 }], "/api/users/99": [new HttpError(404, "/api/users/99")] };
function fakeGet(url, attempt) {
const answer = scripted[url][Math.min(attempt - 1, scripted[url].length - 1)];
if (answer instanceof Error) throw answer;
return answer;
}
function getWithRetry(url, maxAttempts = 3) {
for (let attempt = 1; ; attempt++) {
try {
const body = fakeGet(url, attempt);
console.log(` ${url} attempt ${attempt}: ok`);
return body;
} catch (e) {
const canRetry = e.retryable === true && attempt < maxAttempts;
console.log(` ${url} attempt ${attempt}: ${e.name} - ${e.message}${canRetry ? " -> retrying" : ""}`);
if (!canRetry) throw new AppError(`GET ${url} failed after ${attempt} attempt(s)`, { cause: e });
}
}
}
console.log(getWithRetry("/api/orders"));
try {
getWithRetry("/api/users/99");
} catch (e) {
console.log(`${e.message} | cause: ${e.cause.name} status=${e.cause.status}`);
}
⌨️ Terminal
node retry.js
🖥️ Output
/api/orders attempt 1: TimeoutError - timeout 5000 ms -> retrying
/api/orders attempt 2: HttpError - HTTP 503 for /api/orders -> retrying
/api/orders attempt 3: ok
{ items: 3 }
/api/users/99 attempt 1: HttpError - HTTP 404 for /api/users/99
GET /api/users/99 failed after 1 attempt(s) | cause: HttpError status=404
Playwright exports its own error classes, for example errors.TimeoutError from @playwright/test, so the same instanceof technique works with real browser timeouts.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Create class NotFoundError extends Error that takes a resource name and builds the message "<resource> not found". Throw and catch it, printing the name and message.
Show answer
📄 practice1.js
class NotFoundError extends Error {
constructor(resource) {
super(`${resource} not found`);
this.name = "NotFoundError";
this.resource = resource;
}
}
try {
throw new NotFoundError("Order 451");
} catch (e) {
console.log(e.name, "|", e.message, "|", e instanceof NotFoundError);
}🖥️ Output
NotFoundError | Order 451 not found | trueQ2. Write a base class AppError that sets name automatically, then two subclasses AuthError and DbError. Show that each has the right name without setting it again.
Show answer
📄 practice2.js
class AppError extends Error {
constructor(message) { super(message); this.name = new.target.name; }
}
class AuthError extends AppError {}
class DbError extends AppError {}
console.log(new AuthError("token expired").name, new DbError("connection lost").name);🖥️ Output
AuthError DbErrorQ3. Add a numeric status and a getter isClientError (400–499) to an HttpError class. Test it with 404 and 502.
Show answer
📄 practice3.js
class HttpError extends Error {
constructor(status) {
super(`HTTP ${status}`);
this.name = "HttpError";
this.status = status;
}
get isClientError() { return this.status >= 400 && this.status < 500; }
}
console.log(new HttpError(404).isClientError, new HttpError(502).isClientError);🖥️ Output
true falseQ4. Wrap a TypeError in an error "Checkout step failed" using cause, and print the message and the cause’s name.
Show answer
📄 practice4.js
try {
try {
undefined.total;
} catch (e) {
throw new Error("Checkout step failed", { cause: e });
}
} catch (e) {
console.log(e.message, "<-", e.cause.name, ":", e.cause.message);
}🖥️ Output
Checkout step failed <- TypeError : Cannot read properties of undefined (reading 'total')Q5. Validate an array of prices [10, -5, "abc", 20, -1] and throw one AggregateError listing every invalid entry with its index.
Show answer
📄 practice5.js
const prices = [10, -5, "abc", 20, -1];
const problems = prices
.map((p, i) => (typeof p !== "number" || p < 0 ? new Error(`index ${i}: invalid price ${JSON.stringify(p)}`) : null))
.filter(Boolean);
try {
if (problems.length) throw new AggregateError(problems, `${problems.length} invalid prices`);
} catch (e) {
console.log(e.message);
for (const err of e.errors) console.log(" -", err.message);
}🖥️ Output
3 invalid prices
- index 1: invalid price -5
- index 2: invalid price "abc"
- index 4: invalid price -1Q6. Make JSON.stringify of your custom error include the name, message and a code property.
Show answer
📄 practice6.js
class CodedError extends Error {
constructor(code, message) {
super(message);
this.name = "CodedError";
this.code = code;
}
toJSON() { return { name: this.name, code: this.code, message: this.message }; }
}
console.log(JSON.stringify(new CodedError("E_TIMEOUT", "Page load timed out")));🖥️ Output
{"name":"CodedError","code":"E_TIMEOUT","message":"Page load timed out"}🧠 MCQ Quiz: Custom Errors
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What must a custom error constructor call first?Answer: super(message). super sets message, stack and cause.
- Why set
this.namein a custom error?Answer: So the error type appears in logs and stack traces. Without it the error prints as “Error”. - What does
this.name = new.target.namein a base class do?Answer: Uses the actual subclass name automatically. Every subclass gets the right name. - Why use error codes like E_VALIDATION?Answer: They are stable for code checks even if messages change. Node.js uses codes such as ENOENT.
- With
class NotFound extends HttpError, what isnew NotFound() instanceof HttpError?Answer: true. Check the most specific class first. - What does
AggregateErrorhold?Answer: An array of errors in its errors property. Promise.any throws it when all promises fail. - What does
JSON.stringify(new Error("x"))return?Answer: “{}”. Add toJSON or convert errors explicitly. - How do you attach the original error when wrapping it?Answer: new Error(“context”, { cause: original }). The cause option was added in ES2022.
- Which error should a retry helper usually NOT retry?Answer: HTTP 404 Not Found. Client errors will fail again; fix the request instead.
- When is returning a result object better than throwing?Answer: When failure is a normal, expected outcome. For example, a search that finds nothing.
💼 Interview Questions and Answers
Q1. How do you create a custom error class in JavaScript?
📄 payment-error.js
class PaymentError extends Error {
constructor(message, { orderId, cause } = {}) {
super(message, { cause });
this.name = "PaymentError";
this.orderId = orderId;
}
}
const e = new PaymentError("Card declined", { orderId: 451 });
console.log(e.name, e.message, e.orderId, e instanceof PaymentError, e instanceof Error);
⌨️ Terminal
node payment-error.js
🖥️ Output
PaymentError Card declined 451 true true
Extend Error, call super with the message (and optional cause), set name, and add context properties. Callers can then use instanceof and read the extra fields.
Q2. Why are custom errors useful in a test framework?
They make failures diagnosable and actionable: an ApiError carries the URL, status and response snippet; a DataSetupError says which fixture failed; a ConfigError points at a missing environment variable. Retry logic and reporters can branch on the type, and reports group failures by category (product bug, test bug, environment issue).
Q3. What is the error cause feature and why use it?
ES2022 added an options argument to Error: new Error(message, { cause }). It keeps the original error when you wrap it with a higher-level message, so you get both the business context (“checkout setup failed”) and the root technical reason (a JSON SyntaxError) without string concatenation. Node.js prints the chain when the error is uncaught.
Q4. How would you report several validation failures at once?
Collect the individual problems into an array while validating, then throw one AggregateError(errors, message) (or a custom ValidationError with an issues array). Callers iterate error.errors to show every problem. Test frameworks offer the same idea with soft assertions, such as Playwright’s expect.soft.
❓ Frequently Asked Questions
🤔 Should every error in my project be a custom class?
No. Create custom classes for categories that callers handle differently (HTTP, validation, timeout, configuration). Built-in types are fine for programming bugs.
🤔 Does instanceof work with custom errors across modules?
Yes, as long as both sides use the same class from the same module. Duplicate copies of a library (different versions) can break instanceof, which is one reason to also set name or code.
🤔 What is Error.captureStackTrace?
A V8 (Node.js and Chrome) function that sets a stack on any object and can hide frames. With class extends Error and super() you rarely need it.
🤔 Can I add a custom error to a Playwright test?
Yes. Throw it from helpers or page objects; Playwright reports its name and message, and expect(() => fn()).toThrow(MyError) checks the type.
🏁 Summary
- Custom errors extend
Error, callsuper(message, options)and setname(automatically withnew.target.name). - Add context (status, url, field) and stable codes so callers can decide what to do.
- Shallow hierarchies let code catch broadly or narrowly; check the most specific
instanceoffirst. - Chain errors with
causeand report several failures at once withAggregateError. - Add
toJSONfor logs and reports, never include secrets, and return results instead of throwing for expected outcomes.
Next, continue with Lesson 45: Debugging in VS Code and DevTools.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in