Sub topic 4
Giving Your Error a Proper Name
This chapter assumes you can already write a class that extends Error and passes message and options to super, as shown in the previous chapter. It also assumes you are comfortable with ES2015 classes, property descriptors, and running snippets in Node.js or a browser console.
A subclass of Error gets the right prototype chain for free. It does not get the right name. That gap matters more than it looks, because name is the first thing that shows up in logs, stack traces, and String(err) output. This chapter covers where name comes from, the ways to set it, and the problems each way brings.
The Default Name Problem
name is not created on each error instance. It is inherited from Error.prototype.name, which holds the string 'Error'. Built-in subclasses such as TypeError override it on their own prototypes. Your class does not, so it inherits 'Error'.
class ValidationError extends Error {}
const err = new ValidationError('Email is required');
console.log(err instanceof ValidationError); // true
console.log(err.name); // 'Error'
console.log(String(err)); // 'Error: Email is required'
console.log(Object.hasOwn(err, 'name')); // false
console.log(Object.hasOwn(TypeError.prototype, 'name')); // trueThe instanceof check works, but anyone reading a log line sees a plain Error. In a production log that collects thousands of entries, that difference decides whether a failure can be grouped and searched.
Where name Is Used
Several parts of the platform read name. None of them look at the class itself.
Error.prototype.toStringbuilds"name: message". It is called byString(err), by template literals, and by string concatenation.- In V8 (Node.js, Chromium), the first line of
err.stackis built fromnameandmessage. Firefox and Safari leave the header out ofstackand only list frames, but their consoles still display the name. - Node's
util.inspect, whichconsole.loguses, prints the stack and so shows the name. - Code that cannot rely on
instanceof, such as code checking errors from another realm or theDOMExceptionnamed'AbortError', compareserr.nameas a string.
The toString algorithm has a few edge cases that are worth knowing:
const e = new Error('boom');
e.name = '';
console.log(String(e)); // 'boom'
const f = new Error();
f.name = 'Timeout';
console.log(String(f)); // 'Timeout'Four Ways to Set the Name
1. Assign in the constructor
This is the most common pattern, and it is the one used throughout this tutorial:
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(Object.keys(err)); // [ 'name' ]
console.log(JSON.stringify(err)); // '{"name":"ValidationError"}'The assignment creates an own, enumerable name property on every instance. That is often fine, and it even helps, because JSON.stringify and object spread now include the name. Keep the side effect in mind, though. Instances of your class now look different under Object.keys than built-in errors do, where name stays hidden on the prototype.
A class field (name = 'ValidationError'; in the class body) behaves the same way. Fields are defined right after super() returns, as own enumerable properties.
2. Define it on the prototype
This approach matches what the built-ins do. Set the name once on the prototype and make it non-enumerable:
class ValidationError extends Error {}
Object.defineProperty(ValidationError.prototype, 'name', {
value: 'ValidationError',
writable: true,
enumerable: false,
configurable: true,
});
const err = new ValidationError('Email is required');
console.log(String(err)); // 'ValidationError: Email is required'
console.log(Object.keys(err)); // []The instance stays clean, and the code costs nothing per instance. The downside is that the definition sits outside the class body, where it is easy to forget when someone copies the class. A plain assignment such as ValidationError.prototype.name = '...' also works, but it creates an enumerable property, which for...in loops over instances will pick up.
3. Use a getter
Accessors declared in a class body go on the prototype and are non-enumerable, so this keeps the name inside the class:
class ValidationError extends Error {
get name() {
return 'ValidationError';
}
}
console.log(String(new ValidationError('bad'))); // 'ValidationError: bad'There is a trap here. Class bodies run in strict mode, and in strict mode assigning to a property that only has a getter throws an error. If a base class assigns this.name, a subclass that uses a getter breaks:
class AppError extends Error {
constructor(message) {
super(message);
this.name = 'AppError'; // finds the subclass getter on the prototype chain
}
}
class PaymentError extends AppError {
get name() {
return 'PaymentError';
}
}
try {
new PaymentError('Card declined');
} catch (e) {
console.log(e instanceof TypeError); // true: cannot set property name, it only has a getter
}Choose one approach for the whole hierarchy. Do not mix a getter with assignments.
4. Derive it from the class
A base class can name every subclass automatically:
class AppError extends Error {
constructor(message, options) {
super(message, options);
this.name = new.target.name;
}
}
class PaymentError extends AppError {}
class InventoryError extends AppError {}
console.log(new PaymentError('Card declined').name); // 'PaymentError'
console.log(new InventoryError('Out of stock').name); // 'InventoryError'new.target is the constructor that new was called on, so it refers to the most derived class even when the code runs inside AppError. this.constructor.name gives the same result in normal code.
Comparing the Approaches
| Approach | Where name lives | Enumerable | Survives minification | Main risk |
|---|---|---|---|---|
| `this.name = '...'` in constructor | Each instance | Yes | Yes | Appears in `Object.keys` and JSON |
| Class field | Each instance | Yes | Yes | Same as above |
| `defineProperty` on prototype | Prototype | No | Yes | Separated from the class body |
| Getter | Prototype | No | Yes | `TypeError` if any constructor assigns `name` |
| `new.target.name` | Each instance | Yes | Only with keep-names | Mangled names in bundles |
For most application code, a string literal assigned in the constructor is the simplest choice and the hardest to break. Use the prototype approach when the error objects should look exactly like built-in ones, for example in a library whose consumers inspect or serialize errors.
Timing: Set the Name Early
In V8, the header line of stack comes from the name and message values at the point the stack string is formatted. Setting name in the constructor is early enough, and every approach above meets that condition. If you change name after something has already read err.stack, the stack may still show the old name while String(err) shows the new one. This leads to confusing logs where the stack and the message disagree. Do not rename errors after you create them. If you need a different name, wrap the error in a new one, which is covered in the chapters on cause.
Common Mistakes
- Forgetting the name entirely. Every custom error then prints as
Error, and log grouping fails without any warning. - Copying a class and leaving the old name string, for example a
NotFoundErrorthat reports itself as'HttpError'. A base-classnew.target.nameprevents this, at the cost of the minification issue. - Setting
namebeforesuper(). This throws aReferenceError, becausethisdoes not exist untilsuperreturns. - Using
nameas the only signal for control flow inside one realm. Preferinstanceofthere, and keepnamefor humans and for cases that cross realms.
Exercise
A teammate writes class RateLimitError extends Error {} and logs String(new RateLimitError('Slow down')). What is printed, and why?
Show answer
It prints "Error: Slow down". The class never defines name, so the lookup goes up the prototype chain to Error.prototype.name, which is 'Error'.
Exercise
You set the name with this.name = 'QuotaError' in the constructor. What does JSON.stringify(new QuotaError('Over limit')) return, and what would change if you used Object.defineProperty on QuotaError.prototype with enumerable: false?
Show answer
With the constructor assignment it returns '{"name":"QuotaError"}', because the assignment creates an own enumerable property, while message and stack are non-enumerable. With the non-enumerable prototype property it returns '{}', because name is no longer an own enumerable property.
Exercise
Your base class sets this.name = new.target.name. After a production build, the logs show errors named 't' and 'n'. What happened, and what are two fixes?
Show answer
The minifier renamed the classes, so new.target.name returns the mangled names. Fix it by enabling keep-names in the bundler (Terser keep_classnames or esbuild --keep-names), or by writing an explicit string literal for the name in each class.
Exercise
Why does defining get name() in a subclass throw when the base class constructor runs this.name = 'AppError'?
Show answer
Class code runs in strict mode. The assignment finds the getter-only accessor on the subclass prototype through the prototype chain, and in strict mode assigning to an accessor that has no setter throws a TypeError instead of creating an own property.