Sub topic 5
Carrying Extra Data: Codes, Statuses, and Context
This chapter assumes you can already write a custom error class with class ... extends Error, call super(message, options), and set this.name. Here you will add structured fields to that class, so that the code handling the error can read facts directly instead of parsing the message text.
Why the message is not enough
A message such as "Email is required" is written for a human reader. Code that has to decide what happens next (return a 400 response, highlight a form field, retry) needs data it can compare reliably. If that data lives only inside the message string, a small change to the wording can break every check that depends on it.
The fix is to add your own properties in the constructor, after super() returns.
class ValidationError extends Error {
constructor(message, { field, value, ...options } = {}) {
super(message, options);
this.name = 'ValidationError';
this.code = 'E_VALIDATION';
this.field = field;
this.value = value;
}
}
const err = new ValidationError('Email is required', { field: 'email', value: '' });
console.log(err.code); // 'E_VALIDATION'
console.log(err.field); // 'email'
console.log(Object.keys(err)); // [ 'name', 'code', 'field', 'value' ]
console.log(JSON.stringify(err));
// {"name":"ValidationError","code":"E_VALIDATION","field":"email","value":""}The constructor takes the custom fields out of the options object and passes everything else to super. If a caller supplies cause, it still reaches the Error constructor. Assignments like this.code = ... create own, enumerable properties, which is why they appear in Object.keys and JSON.stringify. The built-in message and stack properties are non-enumerable, so they do not appear. A later chapter covers serialization in full.
Common field conventions
| Field | Typical value | Purpose |
|---|---|---|
| `code` | `'E_VALIDATION'`, `'ERR_TIMEOUT'` | A stable, machine-readable identifier. Node.js uses this convention (`'ENOENT'`, `'ERR_INVALID_ARG_TYPE'`). |
| `status` | `404`, `503` | The HTTP status that should be sent or that was received. |
| `field` / `details` | `'email'`, `{ min: 8 }` | Context about which input failed and why. |
| `retryable` | `true` / `false` | Tells callers whether trying again might succeed. |
Checking err.code === 'E_VALIDATION' also works when an error crosses a boundary where instanceof fails, for example between iframes, between duplicated package copies, or after the error has been deserialized from JSON.
Common mistakes
- Touching
thisbeforesuper(). In a derived class,thisdoes not exist untilsuperreturns. Accessing it earlier throws aReferenceError. - Dropping
options. A constructor that callssuper(message)and ignores the second argument silently discardscause. - Storing secrets. Errors end up in logs and monitoring tools. Never attach passwords, tokens, or full request bodies.
- Storing live objects. Sockets, database connections, and large buffers make errors hard to log and can keep memory alive. Store identifiers instead, such as
userId: 42. - Overwriting built-ins. Avoid using
message,stack, orcauseas names for your own data.
Exercise
Write a RateLimitError class whose constructor takes (retryAfterSeconds, options). It should set name to 'RateLimitError', code to 'E_RATE_LIMIT', status to 429, and store retryAfterSeconds. The message should read "Rate limit exceeded, retry in N s". Make sure a cause passed in options is kept.
Show answer
class RateLimitError extends Error { constructor(retryAfterSeconds, options) { super(Rate limit exceeded, retry in ${retryAfterSeconds} s, options); this.name = 'RateLimitError'; this.code = 'ERATELIMIT'; this.status = 429; this.retryAfterSeconds = retryAfterSeconds; } } Passing options straight to super keeps any cause.
Exercise
Why might if (err.code === 'E_VALIDATION') keep working in places where if (err instanceof ValidationError) fails?
Show answer
instanceof depends on the prototype chain, and that chain is lost when an error is serialized to JSON, comes from another realm such as an iframe, or comes from a duplicate copy of a package. A string code is plain data, so it survives all of these cases.