Custom error classes
A custom error is a class that extends Error and adds what the handler needs: the field that failed, the code a client reads, the record that could not be saved. Extending the built-in class keeps everything Error already does, so the value still has a message, a stack and a place in the prototype chain.
The lesson starts with the smallest subclass and the two lines it needs, then takes the name field, the cause option that keeps an original error reachable, and the instanceof checks that make a handler pick one kind of failure out of several. The next lesson builds the patterns on top of these classes.
A class that extends Error
A subclass calls super(message) in its constructor, which runs the Error constructor and sets the message and the stack, and then adds its own fields. Calling super first is not a style rule: before it runs there is no this to write to.
The file validation.mjs:
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
const error = new ValidationError('email', 'the address has no @');
console.log('the name:', error.name);
console.log('the message:', error.message);
console.log('the field:', error.field);
console.log('it is a ValidationError:', error instanceof ValidationError);
console.log('it is an Error:', error instanceof Error);
console.log('it is a TypeError:', error instanceof TypeError);
node validation.mjs
the name: ValidationError
the message: the address has no @
the field: email
it is a ValidationError: true
it is an Error: true
it is a TypeError: false
The instance answered to its own class and to Error, and refused TypeError, which is a different branch of the same tree. The class is used exactly like the built-in ones: throw new ValidationError('email', '...'), and the handler decides what to do. The lesson on inheritance explains where that chain comes from.
The name field
Error puts name on the prototype with the value Error, and a subclass inherits it unless it sets its own. The field is what String(error) and every log line print before the message, so a subclass without it is reported as a plain error. The program below compares the two.
The file name.mjs:
class PlainError extends Error {}
class NamedError extends Error {
name = 'NamedError';
}
const plain = new PlainError('one');
const named = new NamedError('two');
console.log('without a name field:', plain.name);
console.log('with a name field:', named.name);
console.log('the log line without it:', String(plain));
console.log('the log line with it:', String(named));
console.log('both are Errors:', plain instanceof Error, named instanceof Error);
node name.mjs
without a name field: Error
with a name field: NamedError
the log line without it: Error: one
the log line with it: NamedError: two
both are Errors: true true
A class field writes the name once per instance, which is the shortest form; assigning this.name in the constructor does the same. A stack trace begins with the name as well, so the fields set here are the first thing a reader of the log sees.
The cause option
A layer that fails because a layer below it failed should keep both errors. The second argument of the constructor, { cause }, stores the original as error.cause, so the message can describe the operation while the cause keeps the reason and its stack. The field is part of the Error class itself and needs no subclass.
The file cause.mjs:
function load(name) {
try {
throw new Error(`cannot open ${name}`);
} catch (cause) {
throw new Error('the settings could not be loaded', { cause });
}
}
try {
load('app.json');
} catch (error) {
console.log('the message:', error.message);
console.log('the cause:', error.cause.message);
console.log('the cause is an Error:', error.cause instanceof Error);
console.log('the cause has no cause:', error.cause.cause === undefined);
}
node cause.mjs
the message: the settings could not be loaded
the cause: cannot open app.json
the cause is an Error: true
the cause has no cause: true
The outer message says what the program was doing and the inner one says what went wrong. A chain of these can be walked with a loop that follows error.cause until it is undefined, which is how a log line names every layer at once.
instanceof through the chain
A handler that knows several kinds of failure asks instanceof in order from the most specific class to the general one. The check walks the prototype chain, so an instance of a subclass answers true for its own class and for Error, and the order of the branches matters as soon as one class extends another.
The file chain.mjs:
class NotFound extends Error {
constructor(what) {
super(`${what} was not found`);
this.name = 'NotFound';
}
}
class PermissionDenied extends Error {
constructor(what) {
super(`${what} is not readable`);
this.name = 'PermissionDenied';
}
}
function read(name) {
if (name === 'secret.txt') {
throw new PermissionDenied(name);
}
if (name.endsWith('.txt')) {
return `contents of ${name}`;
}
throw new NotFound(name);
}
for (const name of ['notes.txt', 'secret.txt', 'notes.bin']) {
try {
console.log(read(name));
} catch (error) {
if (error instanceof PermissionDenied) {
console.log('skipped:', error.message);
} else if (error instanceof NotFound) {
console.log('missing:', error.message);
} else {
throw error;
}
}
}
node chain.mjs
contents of notes.txt
skipped: secret.txt is not readable
missing: notes.bin was not found
The catch handled the two kinds it knew and rethrew anything else, which is the rule that keeps a handler honest. The next lesson takes that rule further: several problems collected in one pass, an error wrapped with its cause, and the programs where a catch is the wrong tool altogether.
Exercises
- Add a code field to ValidationError and print it where the error is caught.
- Remove this.name = 'ValidationError' and print String(error). Which name appears?
- Make NotFound extend a new class FileError and check that an instance is still an Error. Which branch of the handler catches it now?
- Throw a low-level error, wrap it with cause, then print both messages in one line with a loop.
- Write a handler that treats any error which is not a ValidationError as a bug and rethrows it. What does the program print for a validation failure and for a programming mistake?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a class that extends Error keep?
Answer
The message, the stack and the place in the prototype chain
The subclass runs the Error constructor, so every field and the chain to Error stay as they were.
-
Why is
this.nameset in the constructor of a subclass?Answer
Without it, logs and stacks print the name Error
The name comes from the prototype, and a subclass inherits the one from Error until it sets its own.
-
What does the second argument of
new Error(message, { cause })do?Answer
It keeps the original error as error.cause
The cause field keeps the reason of the layer below, with its own message and stack.
-
A variable holds an instance of ValidationError. What does
error instanceof Erroranswer?Answer
true, because the chain goes through Error
instanceof walks the prototype chain, and a subclass sits above Error in it.
-
What does this program print?
class NotFound extends Error { constructor(what) { super(what + " was not found"); this.name = "NotFound"; } } const error = new NotFound("file"); console.log(error.name, "|", error.message);Answer
NotFound | file was not found
The name is the subclass name and the message is the text passed to super.
-
What does this program print?
class A extends Error {} const error = new A("one"); console.log(error.name, String(error));Answer
Error Error: one
The subclass sets no name, so the inherited one is Error, and String uses it before the message.
-
What does this program print?
try { try { throw new Error("inner"); } catch (cause) { throw new Error("outer", { cause }); } } catch (error) { console.log(error.message, "and", error.cause.message); }Answer
outer and inner
The outer error keeps the inner one in cause, and both messages are readable.
-
Which check tells a NotFound apart from a PermissionDenied?
Answer
instanceof NotFound
The class is the only thing that identifies the kind, and instanceof reads the chain.
-
What does
super(message)do in the constructor of an error subclass?Answer
Runs the Error constructor, which sets message and stack
Without the call there is no this and no message, and the constructor throws.
-
What does this program print?
class E extends Error { name = "E"; } const error = new E("x"); console.log(error instanceof E, error instanceof Error, error.name);Answer
true true E
A class field writes the name per instance, and the chain answers true for both classes.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev