Sub topic 3
Creating a Custom Error Class
This chapter assumes you know ES2015 class syntax (extends and super), throw and try/catch, and how to run code in Node.js or the browser console. It also builds on the previous chapters' coverage of name, message, and stack.
Why Subclass Error
You can throw any value in JavaScript, including strings and plain objects. Those values have no stack trace, they fail instanceof Error checks, and logging tools often display them poorly. A class that extends Error keeps everything the built-in gives you. It also gives the error a type of its own that your catch blocks can test for.
The Minimal Pattern
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'The super(message, options) call does the real work. It runs the Error constructor, which:
- sets
messageas an own property, - records
stack(in all major engines), - defines
causeifoptionscontains acausekey.
Setting this.name makes the class name appear in toString() output and in stack traces. The next chapter covers it in detail.
How the Prototype Chain Fits Together
Because ValidationError.prototype inherits from Error.prototype, a check against either class returns true. Inherited methods such as toString() keep working as well.
Common Mistakes
Touching `this` before `super`
A derived constructor has no this until super() returns. Code like the following throws a ReferenceError as soon as the constructor runs:
class BrokenError extends Error {
constructor(message) {
this.name = 'BrokenError'; // ReferenceError: must call super first
super(message);
}
}Dropping the options argument
If your constructor accepts only message, the caller's cause is silently lost:
class LossyError extends Error {
constructor(message) {
super(message);
this.name = 'LossyError';
}
}
const original = new Error('disk full');
const wrapped = new LossyError('Save failed', { cause: original });
console.log(wrapped.cause); // undefinedAlways forward options to super, even if you don't need cause today. Later chapters depend on it.
Omitting the constructor entirely
A subclass with no constructor is valid. JavaScript generates one that forwards all arguments to super, so both message and cause work. You still need a constructor to set name on the instance, which is why the minimal pattern above defines one.
Quick Reference
| Step | Why |
|---|---|
| `extends Error` | Inherits `stack`, `toString()`, and `instanceof Error` |
| `super(message, options)` | Sets `message`, records `stack`, keeps `cause` |
| `this.name = '...'` after `super` | Shows the class name in output |
Exercise
A teammate writes class TimeoutError extends Error { constructor(ms) { super(Timed out after ${ms} ms); this.name = 'TimeoutError'; } }. Calling new TimeoutError(500, { cause: err }) loses the cause. Rewrite the constructor so the cause is kept.
Show answer
Accept and forward an options argument: constructor(ms, options) { super(Timed out after ${ms} ms, options); this.name = 'TimeoutError'; }. The Error constructor then defines cause from options.cause.
Exercise
Without running it, what does new ValidationError('x') instanceof Error return, and why?
Show answer
It returns true. ValidationError.prototype inherits from Error.prototype, so Error.prototype is on the instance's prototype chain.