Custom Error Classes
Extending Error lets a catch block tell one kind of failure from another, which is what turns error handling from guesswork into a decision.
A class extending Error gives you a type you can check with instanceof, plus any fields the caller needs. Set the name, call super with the message, and use the cause option to keep the original failure attached.
EXERCISE
1Why a String Message Is Not Enough
Once more than one thing can fail, the caller needs to know which one did, and a message is the wrong place to record it.
The problem, in the shape it usually appears:
async function saveUser(user) {
if (!user.email.includes("@")) {
throw new Error("Invalid email");
}
const response = await fetch("/api/users", { method: "POST" });
if (!response.ok) {
throw new Error("Request failed");
}
}
Now the caller has to decide what to do:
try {
await saveUser(user);
} catch (err) {
if (err.message === "Invalid email") {
highlightField("email");
} else {
showBanner("Something went wrong");
}
}
That comparison is a string match on a human-readable message. Reword the message for clarity and the handler breaks, with no warning from anything.
A class fixes it:
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
class NetworkError extends Error {
constructor(message, status) {
super(message);
this.name = "NetworkError";
this.status = status;
}
}
try {
await saveUser(user);
} catch (err) {
if (err instanceof ValidationError) {
highlightField(err.field);
} else if (err instanceof NetworkError && err.status >= 500) {
scheduleRetry();
} else {
showBanner("Something went wrong");
}
}
The check is on the type, the message is free to change, and field and status carry the data the handler actually needs.
Three details in that constructor matter:
class ValidationError extends Error {
constructor(message, field) {
super(message); // 1. sets message and captures the stack
this.name = "ValidationError"; // 2. otherwise it says "Error"
this.field = field; // 3. the data the caller needs
}
}
Forget super(message) and the message is empty. Forget this.name and every log line says Error: regardless of type, which makes a production log much harder to scan.
And it composes with the prototype chain from Unit 1:
class AppError extends Error {}
class ValidationError extends AppError {}
const err = new ValidationError("bad");
console.log(err instanceof ValidationError); // true
console.log(err instanceof AppError); // true
console.log(err instanceof Error); // true
A handler can catch broadly with instanceof AppError or narrowly with instanceof ValidationError, because instanceof walks the whole chain. That is the same mechanism as Unit 1, now doing something useful.
Create an error class the moment a caller needs to tell two failures apart. Before that, a plain Error with a good message is enough and a class hierarchy is ceremony. The trigger is a branching catch, not a feeling that the code should look professional.
EXERCISE
2cause, and Not Losing the Original
Wrapping an error to add context usually throws the original away, and one option prevents that.
The instinct, and what it costs:
async function loadDashboard(userId) {
try {
return await fetchDashboard(userId);
} catch (err) {
throw new Error(`Dashboard failed for user ${userId}`);
}
}
The new message is more useful than the old one. It is also all you have: the original error, with its status code, its own message and its stack pointing at the real failure, is gone.
cause keeps it:
catch (err) {
throw new Error(`Dashboard failed for user ${userId}`, { cause: err });
}
try {
await loadDashboard(7);
} catch (err) {
console.log(err.message); // Dashboard failed for user 7
console.log(err.cause.message); // HTTP 503
console.log(err.cause.stack); // where it really happened
}
Modern runtimes print the chain automatically, so a logged error shows both layers with their stacks. That matters because the outer message says what the user was doing and the inner one says what actually broke, and a bug report needs both to be useful.
It works in a custom class too, by passing the options through:
class AppError extends Error {
constructor(message, options) {
super(message, options); // forwards { cause }
this.name = "AppError";
}
}
throw new AppError("Checkout failed", { cause: paymentError });
And walking the chain is sometimes worth doing:
function rootCause(err) {
let current = err;
while (current.cause) {
current = current.cause;
}
return current;
}
console.log(rootCause(err).message); // the original failure
When to wrap and when to let it through:
// Wrap when you can add context the caller cannot work out:
throw new Error(`Failed to import row ${rowNumber}`, { cause: err });
// Let it through when you have nothing to add:
const data = await fetchData(); // no try at all
A wrapper that only restates the original is noise in the log and an extra stack frame to read past. The test is whether your message contains information that was not available further down, such as which row, which user, which retry attempt.
One thing cause is not:
// It does not make the error recoverable, and it does not
// change the type. A caller still checks instanceof on the
// OUTER error, and reaches for .cause only for diagnosis.
Pro Tip: Add
{ cause: err }every single time you wrap. It costs fifteen characters and it is the difference between a log that says which user failed and one that also says why. There is no situation where discarding the original error is better than keeping it attached.
EXERCISE
3A Hierarchy Small Enough to Use
Most applications need three or four error types, not fifteen, and the useful split is by who should react.
It is tempting to create a class per failure. That produces a taxonomy nobody remembers and catch blocks that miss cases.
A better organising question: who is supposed to do something about this?
Three categories cover most applications:
class AppError extends Error {
constructor(message, options) {
super(message, options);
this.name = new.target.name; // subclasses get their own name free
}
}
// The user can fix it: bad input, missing field, wrong format.
class ValidationError extends AppError {
constructor(message, field) {
super(message);
this.field = field;
}
}
// Nobody can fix it now, but retrying might work.
class TransientError extends AppError {
constructor(message, options) {
super(message, options);
this.retryable = true;
}
}
// A developer has to fix it. The user can only be apologised to.
class BugError extends AppError {}
Note new.target.name in the base constructor. That is the new.target from Unit 1: it holds the class actually being constructed, so every subclass gets the right name without repeating a line.
The handler becomes a short, complete decision:
try {
await submitOrder(order);
} catch (err) {
if (err instanceof ValidationError) {
highlightField(err.field, err.message);
} else if (err instanceof TransientError) {
showRetryButton();
} else {
report(err);
showGenericFailure();
}
}
Three branches and a fallback, and each one corresponds to a different person doing something about it: the user, the system, or you. That is why the split holds up as an application grows, while a split by subsystem or by endpoint does not. Adding a fourth error type later means deciding which existing branch it belongs in, which is usually easy, rather than adding a fourth branch.
Mapping foreign errors at the boundary:
async function apiRequest(url) {
let response;
try {
response = await fetch(url);
} catch (err) {
throw new TransientError("Network unavailable", { cause: err });
}
if (response.status >= 500) {
throw new TransientError(`Server error ${response.status}`);
}
if (response.status === 422) {
const body = await response.json();
throw new ValidationError(body.message, body.field);
}
if (!response.ok) {
throw new BugError(`Unexpected status ${response.status}`);
}
return response.json();
}
Everything above this function now deals in your three types. The details of stop leaking into every caller, which is the real benefit: one place decides what a 422 means.
What to avoid:
// A class per endpoint or per message
class UserNotFoundError extends Error {}
class PostNotFoundError extends Error {}
class CommentNotFoundError extends Error {}
// One type with the detail as data
class NotFoundError extends AppError {
constructor(resource, id) {
super(`${resource} ${id} not found`);
this.resource = resource;
this.id = id;
}
}
If two error types would always be handled identically, they are one type with a field.
