Sub topic 16
Choosing Between Error Classes and Error Codes
This chapter assumes you can write a custom error class with class extends Error, set its name, add fields such as status, and check errors with instanceof in a catch block. It also assumes you know how to wrap an error with the cause option. Earlier chapters covered each of these. Here the question is a design choice. When a new failure needs a way to be identified, should it get its own class, or should it be a plain Error with a code property?
Both approaches work, and mature codebases often use both. The difficulty is choosing on purpose instead of by habit.
The Two Approaches Side by Side
An error code is a stable string or number stored on the error, usually as code. Node.js uses this style for system errors. Reading a missing file rejects with an Error whose code is 'ENOENT':
// Save as read-optional.mjs and run with: node read-optional.mjs
import { readFile } from 'node:fs/promises';
async function readOptional(path) {
try {
return await readFile(path, 'utf8');
} catch (err) {
if (err.code === 'ENOENT') return null;
throw err;
}
}
console.log(await readOptional('./does-not-exist.txt')); // nullAn error class gives each kind of failure its own constructor, and callers pick it out with instanceof:
class NotFoundError extends Error {
constructor(resource, options) {
super(`${resource} not found`, options);
this.name = 'NotFoundError';
}
}
try {
throw new NotFoundError('Order 17');
} catch (err) {
if (err instanceof NotFoundError) {
console.log('Handled:', err.message); // Handled: Order 17 not found
} else {
throw err;
}
}The two checks look alike, but they behave differently in some situations.
Trade-offs That Decide the Choice
| Concern | Error class with `instanceof` | Error code on the error |
|---|---|---|
| Grouping related failures | Built in: a subclass matches its parent's check | Needs prefixes or a lookup table |
| Survives `JSON.stringify` and network hops | No: the class is lost, so you get a plain object | Yes: the code is just a string field |
| Works across realms (iframes, `vm` contexts, workers) | No: each realm has its own constructors | Yes |
| Works with two copies of the same package installed | No: two copies mean two different classes | Yes |
| Typo safety | A misspelled class name throws `ReferenceError` | A misspelled string fails silently |
| Cost of adding a new kind | A new class, export, and import | A new constant |
| Carrying custom fields and behavior | Natural: constructor builds message and fields | Possible, but every throw site repeats the setup |
Two rows deserve more detail.
Identity Does Not Cross Boundaries
instanceof compares prototype chains, so it only works when the error object and the class come from the same loaded copy of the code. An error created in a worker thread, sent over HTTP, read back from a log, or thrown by a duplicate copy of a library in node_modules will fail the check even when it "is" a NotFoundError. A code field is plain data, so it survives all of these. If an error has to leave the process or the package where it was created, plan to identify it by code at that point.
Codes Do Not Form Groups
A class hierarchy lets one catch branch handle a whole family: err instanceof HttpError matches NotFoundError, ConflictError, and any subclass added later. With codes you have to list every member, or adopt a naming scheme such as 'DB_TIMEOUT' and 'DB_CONSTRAINT' and match on the prefix. Prefix matching is fragile because nothing stops someone from adding 'DBX_SOMETHING'.
The Hybrid Most Projects Settle On
A common pattern uses classes for the handling strategy and codes for the specific reason. You create a class only when callers will respond differently to it. Inside each class, a code says exactly what went wrong.
class AppError extends Error {
constructor(code, message, options) {
super(message, options);
this.name = 'AppError';
this.code = code;
}
}
class ValidationError extends AppError {
constructor(code, field, message, options) {
super(code, message, options);
this.name = 'ValidationError';
this.field = field;
}
}
class NotFoundError extends AppError {
constructor(resource, options) {
super('NOT_FOUND', `${resource} not found`, options);
this.name = 'NotFoundError';
}
}
const ErrorCodes = Object.freeze({
EMAIL_REQUIRED: 'EMAIL_REQUIRED',
EMAIL_INVALID: 'EMAIL_INVALID',
NOT_FOUND: 'NOT_FOUND',
});
function validateSignup(input) {
if (!input.email) {
throw new ValidationError(ErrorCodes.EMAIL_REQUIRED, 'email', 'Email is required');
}
if (!input.email.includes('@')) {
throw new ValidationError(ErrorCodes.EMAIL_INVALID, 'email', 'Email is not valid');
}
}
function toHttpResponse(err) {
if (err instanceof ValidationError) {
return { status: 400, body: { code: err.code, field: err.field, message: err.message } };
}
if (err instanceof NotFoundError) {
return { status: 404, body: { code: err.code, message: err.message } };
}
return { status: 500, body: { code: 'INTERNAL', message: 'Internal server error' } };
}
try {
validateSignup({ email: 'not-an-email' });
} catch (err) {
console.log(toHttpResponse(err));
// { status: 400, body: { code: 'EMAIL_INVALID', field: 'email', message: 'Email is not valid' } }
}
console.log(toHttpResponse(new NotFoundError('User 42')).status); // 404
console.log(toHttpResponse(new TypeError('boom')).body.code); // 'INTERNAL'Look at what each part does. The two subclasses exist because the HTTP layer treats them differently (400 versus 404). The two email codes share one class because nothing in this code handles them differently, but a client form needs to know which message to show. The ErrorCodes object turns string typos into undefined, which is easier to spot in review and which TypeScript or a linter can catch. Unknown errors become a generic 500 that does not leak internal messages.
Checking Codes Safely
When you identify errors by code, remember that anything can be thrown, including null, strings, and numbers. Reading err.code on null throws a TypeError inside your catch block. A small guard avoids this, and because it never uses instanceof, it works on errors from other realms or duplicate packages:
function hasCode(err, code) {
return typeof err === 'object' && err !== null && err.code === code;
}
console.log(hasCode(null, 'NOT_FOUND')); // false
console.log(hasCode({ code: 'NOT_FOUND' }, 'NOT_FOUND')); // true (a deserialized error)
console.log(hasCode(new Error('x'), 'NOT_FOUND')); // falseLibraries that are published to npm often export guards like isAppError(err) that check a code or a brand field instead of using instanceof, for exactly the duplicate-package reason described above.
Decision Guide
Guidelines and Common Mistakes
- Keep the hierarchy shallow. One base class for your application or library, plus a handful of subclasses split by handling strategy, covers most needs. Deep trees such as
DbError > DbWriteError > DbUniqueWriteErrorare rarely matched at the middle levels. - Treat codes as public API. Clients, dashboards, and alerts will match on them. Renaming
'EMAIL_INVALID'is a breaking change. Messages can change freely; codes should not. - Do not parse messages. Checking
err.message.includes('not found')breaks as soon as someone rewords or translates the message. That fragility is the main reason codes exist. - Do not mirror every low-level error. Wrap low-level failures at the layer boundary in one of your own classes and keep the original in
cause. Callers should not need to know which driver error codes your database client produces. - Always rethrow what you do not recognize. Whether you match on classes or codes, the final branch should rethrow, or at the outermost boundary, convert the error into a generic failure.
- Set the code in the constructor, not at throw sites. If every
throwhas to remembererr.code = ..., some will forget. A subclass that fixes its code, likeNotFoundErrorabove, removes that risk.
Exercise
A payment library throws CardDeclinedError, CardExpiredError, and InsufficientFundsError, all subclasses of PaymentError. Every caller handles all three the same way: show "Payment failed" with a specific reason. Users report that err instanceof PaymentError sometimes returns false. What is a likely cause, and how would you redesign the errors?
Show answer
Two copies of the library are probably installed (for example, different versions pulled in by different dependencies), so the error was built from a different PaymentError class than the one the caller imported. Since callers do not handle the three cases differently, collapse them into one PaymentError class with a stable code such as 'CARD_DECLINED', 'CARD_EXPIRED', or 'INSUFFICIENT_FUNDS'. Export a guard like isPaymentError(err) that checks a code or brand field instead of using instanceof, so it works across duplicate copies.
Exercise
A teammate writes catch (err) { if (err.code === 'TIMEOUT') retry(); else throw err; }. Name a case where this catch block itself throws a different error, and fix it.
Show answer
If the code being called throws null or undefined, reading err.code throws a TypeError, which hides the original failure. Guard the access: if (typeof err === 'object' && err !== null && err.code === 'TIMEOUT') retry(); else throw err;, or use optional chaining: if (err?.code === 'TIMEOUT').
Exercise
Your API must return errors as JSON to a mobile app, and the server maps errors to HTTP responses. Which fields should the JSON body carry so the app can react correctly, and why should it not rely on the error's class name?
Show answer
Send a stable code (and any structured fields such as field) along with a human-readable message. The HTTP status travels in the response itself. The class does not survive serialization, and name is an internal detail that may change during refactoring, while the code is documented API the app can match on safely.