Sub topic 4
Giving Your Error a Proper Name
This chapter assumes you can write a class that extends Error and calls super(message, options), as covered in the previous chapter. It also assumes you can run code in Node.js or a browser console.
Why a Subclass Still Says "Error"
A subclass of Error gets its name from the prototype chain unless you set it yourself. Error.prototype.name is the string 'Error', so every custom error reports itself as a plain Error by default:
class ValidationError extends Error {}
const err = new ValidationError('Email is required');
console.log(err.name); // 'Error'
console.log(String(err)); // 'Error: Email is required'
console.log(err instanceof ValidationError); // trueinstanceof still works, but the text output loses the class. Error.prototype.toString() builds its result from name and message. In Node.js and Chromium, the first line of stack uses the same pair. Logs, crash reports, and unhandled-rejection messages all show Error: .... Readers of those logs then can't tell a validation failure from any other failure.
Setting name in the Constructor
The common fix is to assign name right after super():
class ValidationError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'ValidationError';
}
}
const err = new ValidationError('Email is required');
console.log(String(err)); // 'ValidationError: Email is required'
console.log(err.stack.split('\n')[0]); // 'ValidationError: Email is required' (Node.js)V8 formats the stack header lazily, so a name set inside the constructor still appears in stack. SpiderMonkey (Firefox) leaves the header out of stack entirely. That doesn't affect toString().
Alternatives and Their Trade-offs
| Approach | Upside | Downside |
|---|---|---|
| `this.name = 'ValidationError'` | Simple and explicit, survives minification | Creates an enumerable own property, so it appears in `Object.keys` and `JSON.stringify` |
| `this.name = this.constructor.name` | Subclasses get a correct name automatically | Minifiers such as Terser rename classes unless `keep_classnames` is on, so you get names like `'t'` |
| Define `name` on the prototype | Non-enumerable, matches how built-ins do it | More verbose |
The prototype approach looks like this:
class ValidationError extends Error {}
Object.defineProperty(ValidationError.prototype, 'name', {
value: 'ValidationError',
writable: true,
enumerable: false,
configurable: true,
});
console.log(String(new ValidationError('bad'))); // 'ValidationError: bad'
console.log(Object.keys(new ValidationError('bad'))); // []Common Mistakes
- Setting
namebefore callingsuper()throws aReferenceError, becausethisis not available untilsuper()returns. - A subclass of your subclass inherits the parent's string literal. Every class in a hierarchy needs its own assignment.
- Using
namefor control flow, as inerr.name === 'ValidationError', is fragile. Usenamefor humans andinstanceoffor code.
Exercise
A teammate writes class TimeoutError extends Error { constructor(ms) { super(Timed out after ${ms} ms); this.name = this.constructor.name; } }. In development, logs show "TimeoutError: Timed out after 500 ms", but production logs show "e: Timed out after 500 ms". What causes this, and what are two ways to fix it?
Show answer
The production bundle is minified, and the minifier renamed the class to e, so this.constructor.name returns 'e'. One fix is to assign a string literal: this.name = 'TimeoutError'. Another is to configure the minifier to keep class names, for example Terser's keep_classnames: true. Defining a non-enumerable name on TimeoutError.prototype with a literal value also works.
Exercise
Why does Object.keys(err) include 'name' for an error that sets this.name in its constructor, but not for a plain new Error('x')?
Show answer
Assigning this.name creates an own enumerable property on the instance. A plain Error has no own name. It reads name from Error.prototype, where the property is inherited and non-enumerable, so Object.keys skips it.