Sub topic 6
Defining Your Own Error Classes
The built-in types such as TypeError and RangeError describe problems with the language itself: a value of the wrong type, or a number out of range. They don't describe problems in your application, such as "this form field is invalid," "this user does not exist," or "the payment provider refused the charge." A custom error class lets you give those failures a name and attach the data that code handling them will need.
This chapter assumes you know the class syntax (including extends and super), the throw statement, try/catch, and the name, message, and stack properties of Error from earlier chapters.
Why Not Just Throw a Plain Error?
You can signal any failure with new Error('something went wrong'). The trouble begins when the code that catches the error has to decide what to do. With a plain Error, the only way to tell failures apart is to inspect the message text:
try {
saveUser({ age: -1 });
} catch (err) {
if (err.message.startsWith('Invalid')) {
// fragile: breaks as soon as someone rewords the message
}
}
function saveUser(user) {
if (user.age < 0) throw new Error('Invalid age');
}Messages are written for people. Someone will reword or translate them, and matching on them is brittle. A custom class gives the catching code a stable type to check, plus structured fields it can read without parsing text.
The Basic Pattern
A custom error is a class that extends Error, calls super(message), sets name, and adds any extra fields:
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
function validateAge(age) {
if (!Number.isInteger(age) || age < 0) {
throw new ValidationError('Age must be a non-negative integer', 'age');
}
return age;
}
try {
validateAge(-1);
} catch (err) {
console.log(err.name); // 'ValidationError'
console.log(err.message); // 'Age must be a non-negative integer'
console.log(err.field); // 'age'
console.log(err instanceof ValidationError); // true
console.log(err instanceof Error); // true
console.log(err.stack.split('\n')[0]); // 'ValidationError: Age must be a non-negative integer'
}Each line in the constructor does a specific job:
| Line | What it does | What happens if you leave it out |
|---|---|---|
| `super(message)` | Runs the `Error` constructor, which sets `message` and captures `stack` | Using `this` throws a `ReferenceError` before the error is even built |
| `this.name = '...'` | Sets the label shown in logs and at the start of `stack` | `name` is inherited from `Error.prototype` and reads `'Error'` |
| `this.field = field` | Adds data the handler can use | Handlers have to dig the information out of the message |
Because ValidationError inherits from Error, the object works anywhere an error is expected. Consoles print it with a stack trace, instanceof Error is true, and logging tools treat it like any other error.
Setting name Reliably
There are three common ways to set name. They differ in how robust they are.
// 1. Assign in the constructor (shown above)
class A extends Error {
constructor(message) {
super(message);
this.name = 'A';
}
}
// 2. Class field: runs right after super() returns
class B extends Error {
name = 'B';
}
// 3. Derive it from the constructor
class C extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
}
}
console.log(new A('x').name, new B('x').name, new C('x').name); // A B COptions 1 and 2 hard-code the string, so the name never changes. Option 3 is convenient in a base class because every subclass inherits the right name automatically. It has one gotcha: minifiers often rename classes, so in a production bundle this.constructor.name can come out as t or e. If error names appear in logs or dashboards you rely on, use explicit strings.
Notice that class B needs no constructor at all. If you only want a distinct type with a distinct name, the implicit constructor passes every argument through to Error.
Building the Message from Data
A custom class can compute its own message, which keeps messages consistent across the codebase:
class NotFoundError extends Error {
constructor(resource, id) {
super(`${resource} with id ${id} was not found`);
this.name = 'NotFoundError';
this.resource = resource;
this.id = id;
}
}
const err = new NotFoundError('User', 42);
console.log(err.message); // 'User with id 42 was not found'
console.log(err.resource); // 'User'
console.log(err.id); // 42Callers pass the facts, and the class decides how to phrase them. The facts also stay available as fields, so a handler can, for example, return an HTTP 404 that includes err.resource without parsing the sentence.
Building a Hierarchy
As an application grows, you usually want one base class for all of your own errors, with specific subclasses under it. A handler can then check broadly ("is this one of ours?") or narrowly ("is this a not-found error?").
class AppError extends Error {
constructor(message, { code = 'APP_ERROR', status = 500, ...options } = {}) {
super(message, options); // forwards options such as cause to Error
this.name = 'AppError';
this.code = code;
this.status = status;
}
}
class ValidationError extends AppError {
constructor(message, field) {
super(message, { code: 'VALIDATION_FAILED', status: 400 });
this.name = 'ValidationError';
this.field = field;
}
}
class NotFoundError extends AppError {
constructor(resource, id) {
super(`${resource} with id ${id} was not found`, { code: 'NOT_FOUND', status: 404 });
this.name = 'NotFoundError';
this.resource = resource;
this.id = id;
}
}
class AuthError extends AppError {
constructor(message = 'Not authenticated') {
super(message, { code: 'UNAUTHENTICATED', status: 401 });
this.name = 'AuthError';
}
}
const e = new NotFoundError('Order', 'A-17');
console.log(e instanceof NotFoundError); // true
console.log(e instanceof AppError); // true
console.log(e instanceof Error); // true
console.log(e.status, e.code); // 404 'NOT_FOUND'The second argument to super is forwarded to the Error constructor so that options such as cause keep working. A later chapter covers cause in detail.
Keep the hierarchy shallow. Two levels (a base class plus specific types) covers most applications. Add a new class only when some handler will actually treat it differently. A class nobody checks for adds code without adding information.
Edge Cases and Gotchas
Errors don't serialize the way you might expect
JSON.stringify includes only own enumerable properties. The Error constructor creates message as non-enumerable, and V8 creates stack the same way, so both disappear from the output:
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
toJSON() {
return { name: this.name, message: this.message, field: this.field };
}
}
const err = new ValidationError('Age must be positive', 'age');
console.log(JSON.stringify(err)); // {"name":"ValidationError","message":"Age must be positive","field":"age"}Without the toJSON method, the output would be {"name":"ValidationError","field":"age"}, and the message would be missing. If your errors are sent to a client or a log pipeline, add toJSON to your base class. Leave stack out of anything a user can see.
Constructor frames in the stack trace
In V8 (Chrome and Node.js), the stack trace of a subclassed error can include a line like at new ValidationError. To start the trace at the place that threw, V8 offers a non-standard helper:
class TimeoutError extends Error {
constructor(message) {
super(message);
this.name = 'TimeoutError';
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, new.target);
}
}
}
console.log(new TimeoutError('Took too long').stack);The typeof check keeps the code safe in engines that don't provide the helper. This step is cosmetic. Skip it unless the extra frame bothers you.
Old transpiler targets break instanceof
If code is compiled down to ES5 (an old TypeScript target, or old Babel setups), the subclass can lose its prototype, so err instanceof ValidationError returns false and custom methods are missing. Compiling to ES2015 or later avoids the problem. If you must target ES5, restore the prototype by hand:
class LegacySafeError extends Error {
constructor(message) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
this.name = 'LegacySafeError';
}
}
console.log(new LegacySafeError('x') instanceof LegacySafeError); // trueinstanceof across realms and package copies
instanceof compares prototype objects. An error created in an iframe, a worker, or a Node.js vm context has a different Error.prototype, so instanceof Error can be false even though the object is an error. The same thing happens when two copies of a library are installed: errors from copy A won't match the class from copy B. In those situations, checking err.name or err.code is more dependable than instanceof.
Throw instances, not classes or strings
throw ValidationError (the class itself) and throw 'invalid' (a string) are both legal JavaScript. Neither gives you a stack trace or the fields you defined. Always throw with new.
Exercise
You define class RateLimitError extends Error { constructor(retryAfter) { super('Rate limit exceeded'); this.retryAfter = retryAfter; } }. A teammate reports that logs show "Error: Rate limit exceeded" instead of "RateLimitError: Rate limit exceeded". Why, and how do you fix it?
Show answer
The class never sets name, so it inherits Error.prototype.name, which is 'Error'. The stack and console output start with that name. Add this.name = 'RateLimitError'; after super(...), or declare the class field name = 'RateLimitError';.
Exercise
Write a PaymentError class that extends the AppError base class from this chapter. It should take an amount and a reason, produce the message "Payment of <amount> failed: <reason>", use the code 'PAYMENT_FAILED' and status 402, and store both values as fields.
Show answer
class PaymentError extends AppError { constructor(amount, reason) { super(Payment of ${amount} failed: ${reason}, { code: 'PAYMENT_FAILED', status: 402 }); this.name = 'PaymentError'; this.amount = amount; this.reason = reason; } } — Then new PaymentError(25, 'card declined') has message 'Payment of 25 failed: card declined', status 402, and is an instance of PaymentError, AppError, and Error.
Exercise
An API server sends errors to clients with res.json(err), and clients receive {"name":"NotFoundError","resource":"User","id":42} with no message. What causes this, and what is the cleanest fix?
Show answer
Serialization goes through JSON.stringify, which includes only own enumerable properties. The Error constructor creates message (and stack) as non-enumerable, so they are left out. Add a toJSON() method to the base error class that returns name, message, code, and any public fields, and leave out the stack.