Sub topic 3
Creating a Custom Error Class
This chapter assumes you know ES2015 class syntax (class, extends, super), how throw and try/catch work, and how to run a script in Node.js or the browser console. It also builds on the previous chapters' description of the name, message, and stack properties.
A custom error class is a class that extends Error. Instances of the class behave like ordinary errors: they have a message and a stack trace, throw and catch handle them as usual, and instanceof Error returns true for them. They also carry an identity of their own, which you can test for. Later chapters build on this one, adding names, extra fields, hierarchies, and causes, so the basic mechanics are worth getting exactly right.
The Minimal Correct Pattern
This is the pattern the rest of the tutorial uses:
class ValidationError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'ValidationError';
}
}
const err = new ValidationError('Email is required');
console.log(err instanceof ValidationError); // true
console.log(err instanceof Error); // true
console.log(err.name); // 'ValidationError'
console.log(String(err)); // 'ValidationError: Email is required'Each of its three lines does a separate job:
extends Errorconnects the class's prototype toError.prototype, which is what makesinstanceof Errorwork.super(message, options)runs the built-inErrorconstructor. That constructor creates the object, setsmessage, captures the stack, and sets upcausewhenoptionscontains one.this.name = ...replaces the inherited name'Error'. The next chapter covers this line in detail.
What super() Actually Does
In a derived class (one that uses extends), this does not exist until super() returns. The parent constructor allocates the object. For Error, that object is a real error instance with the internal [[ErrorData]] slot that engines use to recognize genuine errors.
When super(message, options) runs, the Error constructor:
- Creates a new object whose prototype is
new.target.prototype. Here that isValidationError.prototype, notError.prototype. - Converts
messageto a string and stores it as an own, non-enumerablemessageproperty, but only ifmessageis notundefined. - Defines an own
causeproperty ifoptionsis an object with acausekey. - Captures a stack trace (engine-specific, but present in all major engines).
Step 1 is the important one. Because the object's prototype comes from new.target, the subclass prototype is wired in automatically. ES5-style code had to do this by hand.
You can check the chain yourself:
class ValidationError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'ValidationError';
}
}
const err = new ValidationError('bad input');
console.log(Object.getPrototypeOf(err) === ValidationError.prototype); // true
console.log(Object.getPrototypeOf(ValidationError.prototype) === Error.prototype); // true
console.log(Object.getPrototypeOf(ValidationError) === Error); // true (static side)
console.log(Object.hasOwn(err, 'message')); // true
console.log(Object.keys(err)); // [ 'name' ]The last line shows a detail people often miss. message and stack are non-enumerable own properties, so Object.keys skips them. name appears because a plain assignment creates an enumerable property. This matters when you serialize errors, which a later chapter covers.
Why You Must Forward options
A common mistake is to write the constructor so it accepts only a message:
class LossyError extends Error {
constructor(message) {
super(message); // options are dropped
this.name = 'LossyError';
}
}
const low = new Error('ECONNRESET');
const err = new LossyError('Request failed', { cause: low });
console.log('cause' in err); // false: the original error is goneThe caller passed a cause, and the class silently threw it away. Accepting options and passing it to super costs nothing and keeps the ES2022 cause feature working for every user of your class. Make (message, options) your default signature. If your constructor needs extra arguments, put them first or inside the options object, and still forward options:
class QuotaError extends Error {
constructor(limit, options) {
super(`Quota of ${limit} requests exceeded`, options);
this.name = 'QuotaError';
}
}
const err = new QuotaError(100, { cause: new Error('rate limiter said no') });
console.log(err.message); // 'Quota of 100 requests exceeded'
console.log(err.cause.message); // 'rate limiter said no'When You Can Omit the Constructor
A class with no constructor gets a default one that forwards every argument: constructor(...args) { super(...args); }. This version therefore keeps cause support:
class TimeoutError extends Error {}
const err = new TimeoutError('Took too long', { cause: 'socket idle' });
console.log(err instanceof TimeoutError); // true
console.log(err.cause); // 'socket idle'
console.log(err.name); // 'Error' <- inherited, not 'TimeoutError'The catch is the last line. Without a constructor, or another way to set name, the error prints as Error: Took too long in logs. instanceof still works, but a human reading the output cannot tell which class it was. The next chapter shows several ways to set name, including a prototype-level assignment that removes the need for a constructor.
Common Errors and Edge Cases
Touching this before super()
class BrokenError extends Error {
constructor(message) {
this.code = 'E_BROKEN'; // ReferenceError
super(message);
}
}
try {
new BrokenError('x');
} catch (e) {
console.log(e instanceof ReferenceError); // true
}The ReferenceError is thrown when you construct the error, not when you define the class. This is easy to miss when the constructor only runs on a rare failure path. Always call super first.
Forgetting new
Error('x') works without new, but class constructors do not:
class ValidationError extends Error {}
try {
ValidationError('x');
} catch (e) {
console.log(e instanceof TypeError); // true
console.log(e.message); // e.g. "Class constructor ValidationError cannot be invoked without 'new'"
}If you replace Error('...') calls with a custom class during a refactor, check that every call site uses new.
Messages are coerced to strings
console.log(new Error(42).message); // '42'
console.log(new Error({ id: 7 }).message); // '[object Object]'
console.log(new Error().message); // '' (inherited from Error.prototype)
console.log(Object.hasOwn(new Error(), 'message')); // false
console.log(Object.hasOwn(new Error(''), 'message')); // truePassing an object as the message discards its data. Put structured data in fields instead, which is the topic of a later chapter. Also, an error created with no message has no own message property, so code that checks Object.hasOwn(err, 'message') will behave differently for new MyError() and new MyError('').
Building a message from arguments
Compute the message before calling super, either inline as QuotaError does or in a helper. You cannot use this to build it, because this does not exist yet. Calling a static method or a module-level function is fine.
Why Not the ES5 Pattern?
Older code built error "subclasses" by hand:
function OldStyleError(message) {
this.message = message;
this.name = 'OldStyleError';
this.stack = new Error(message).stack;
}
OldStyleError.prototype = Object.create(Error.prototype);
OldStyleError.prototype.constructor = OldStyleError;
const e = new OldStyleError('legacy');
console.log(e instanceof Error); // true
console.log(Object.prototype.toString.call(e)); // '[object Object]'
console.log(Object.prototype.toString.call(new Error('x'))); // '[object Error]'The pattern partly works, but the object is not a real error. It lacks the internal error slot, so tools that check for genuine errors (some loggers, structured clone, util.types.isNativeError in Node.js) treat it as a plain object. Its stack trace also starts at the wrong frame, and cause only works if you handle it yourself. You cannot fix this by calling Error.call(this, message), because Error ignores this and returns a new object. class extends Error avoids all of these problems.
Summary Table
| Choice | instanceof works | cause kept | name correct |
|---|---|---|---|
| `class X extends Error {}` | Yes | Yes | No (`'Error'`) |
| Constructor with `super(message)` only | Yes | No | Only if set |
| Constructor with `super(message, options)` and `this.name` set | Yes | Yes | Yes |
| ES5 function with `Object.create(Error.prototype)` | Yes | No | Yes, if set |
Exercise
A teammate writes class ParseError extends Error { constructor(line, message) { super(message); this.line = line; } }. Name two problems with it and give a corrected version.
Show answer
First, it drops the options argument, so new ParseError(3, 'Bad token', { cause: err }) loses the cause. Second, it never sets name, so the error prints as "Error: Bad token". A corrected version is: class ParseError extends Error { constructor(line, message, options) { super(message, options); this.name = 'ParseError'; this.line = line; } }.
Exercise
What do Object.hasOwn(new TimeoutError(), 'message') and new TimeoutError().message return, if class TimeoutError extends Error {}?
Show answer
false and ''. When the message is undefined, the Error constructor does not create an own message property, so the read falls through to Error.prototype.message, which is an empty string.
Exercise
Why does this.code = 'E1' placed before super(message) in a derived constructor fail, and when does the failure appear?
Show answer
In a derived class, this is uninitialized until the parent constructor returns, so accessing it throws a ReferenceError. The error is thrown each time the class is instantiated, not when the class is defined, so it may stay hidden until that failure path runs.