Sub topic 1
What an Error Object Contains
Every custom error class you build later in this tutorial starts as a plain Error. Before you extend it, you need to know which properties an Error object has, where each one lives, and which ones the language standard actually guarantees. This chapter covers the three properties you use all the time (name, message, and stack), how they are stored, and some behaviors that surprise people when they first log or inspect an error.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript syntax and functions
throwandtry/catch/finally- Prototypes at a basic level: an object can inherit properties from its prototype
- Running code in Node.js or a browser console
All examples run as plain scripts in Node.js 18 or later, or in a modern browser console.
Creating an Error
You create an error with the Error constructor. Calling it with or without new gives the same result:
const a = new Error('Disk is full');
const b = Error('Disk is full');
console.log(a instanceof Error); // true
console.log(b instanceof Error); // true
console.log(a.message === b.message); // trueCreating an error does not throw it. An Error is an ordinary object until you pass it to throw. You can create one, store it, return it from a function, or put it in an array.
function validate(age) {
if (typeof age !== 'number') {
return new Error('age must be a number');
}
return null;
}
const problem = validate('ten');
console.log(problem.message); // 'age must be a number'The Three Core Properties
message
message is the human-readable description you pass to the constructor. The constructor converts it to a string:
console.log(new Error(42).message); // '42'
console.log(new Error(null).message); // 'null'
console.log(new Error().message); // ''The last line shows an important detail. When you pass no message, or pass undefined, the constructor does not create an own message property. The empty string comes from Error.prototype.message, which is ''.
console.log(Object.hasOwn(new Error('x'), 'message')); // true
console.log(Object.hasOwn(new Error(), 'message')); // false
console.log(Error.prototype.message); // ''name
name identifies the kind of error. For a plain error it is 'Error'. The constructor does not put name on the instance. It is inherited from Error.prototype:
const err = new Error('boom');
console.log(err.name); // 'Error'
console.log(Object.hasOwn(err, 'name')); // false
console.log(Error.prototype.name); // 'Error'This inheritance matters for custom classes. A subclass inherits 'Error' as its name unless you set the name yourself, which a later chapter covers.
stack
stack is a string that describes where the error was created. It usually starts with the result of toString() and then lists one call frame per line:
function inner() {
return new Error('created here');
}
function outer() {
return inner();
}
console.log(outer().stack);
// Error: created here
// at inner (/path/to/script.js:2:10)
// at outer (/path/to/script.js:5:10)
// ...Some facts about stack cause bugs if you don't know them:
- It is not part of the ECMAScript standard. Every major engine supports it, but each one formats it differently. V8 (Node.js, Chrome) writes
at fn (file:line:col). Firefox and Safari writefn@file:line:col. Do not parse stack strings in production code. - It is captured when the error is created, not when it is thrown. If you create an error in one function and throw it in another, the stack points to the place where it was created.
- Where it is stored varies by engine. In V8 it is an own property of the instance. In Firefox it is an accessor on
Error.prototype. Code that relies onObject.hasOwn(err, 'stack')is not portable.
function makeError() {
return new Error('made early');
}
function throwLater(err) {
throw err;
}
try {
throwLater(makeError());
} catch (err) {
// The top frame is makeError, not throwLater.
console.log(err.stack.split('\n')[1]);
}Where the Properties Live
The diagram shows how a plain error instance and Error.prototype split the properties between them in V8.
All of these properties are non-enumerable. They exist, but Object.keys, for...in, object spread, and JSON.stringify all skip them:
const err = new Error('boom');
console.log(Object.getOwnPropertyDescriptor(err, 'message'));
// { value: 'boom', writable: true, enumerable: false, configurable: true }
console.log(Object.keys(err)); // []
console.log({ ...err }); // {}
console.log(JSON.stringify(err)); // '{}'That last line is a common cause of empty error logs. If you send an error through JSON.stringify, the message and stack disappear. A later chapter builds a serializer that fixes this, including for nested causes.
Because the properties are writable, you can change them after creation:
const err = new Error('original');
err.message = 'edited';
console.log(err.message); // 'edited'In V8, editing message after creation does not update the first line of stack, because the stack string was already built. The two can end up disagreeing.
How an Error Becomes a String
Error.prototype.toString() combines name and message. Template literals, string concatenation, and String(err) all call it.
| name | message | toString() result |
|---|---|---|
| `'Error'` | `'boom'` | `'Error: boom'` |
| `'Error'` | `''` | `'Error'` |
| `''` | `'boom'` | `'boom'` |
| `'TimeoutError'` | `'took 5s'` | `'TimeoutError: took 5s'` |
const err = new Error('boom');
console.log(String(err)); // 'Error: boom'
console.log(`Failed: ${err}`); // 'Failed: Error: boom'
err.name = 'TimeoutError';
console.log(String(err)); // 'TimeoutError: boom'console.log(err) behaves differently. Node.js and browsers print the error with an inspector that usually shows the stack and any extra enumerable fields. What you see in the console is therefore not what String(err) gives you, and it is not what ends up in a JSON log.
Throwing Things That Are Not Errors
JavaScript lets you throw any value: strings, numbers, plain objects, even undefined. None of those has a stack, and none passes an instanceof Error check.
try {
throw 'something went wrong';
} catch (err) {
console.log(typeof err); // 'string'
console.log(err instanceof Error); // false
console.log(err.stack); // undefined
}Code that catches errors should not assume err.message exists. A defensive pattern is to normalize the caught value:
function toError(value) {
if (value instanceof Error) return value;
return new Error(`Non-error thrown: ${String(value)}`);
}
try {
throw { code: 42 };
} catch (raw) {
const err = toError(raw);
console.log(err.message); // 'Non-error thrown: [object Object]'
}Common Mistakes
- Expecting
JSON.stringify(err)to contain the message. It returns'{}'becausemessageandstackare non-enumerable andnameis inherited. - Spreading an error to copy it.
{ ...err }copies only enumerable own properties, so you get an empty object. - Parsing
stackto find file names or line numbers. The format differs between engines and between versions of the same engine. - Assuming the stack shows where the error was thrown. It shows where the error was constructed.
- Reading
err.messagein acatchblock without checking the value. Third-party code may throw non-errors.
Exercises
Exercise
What does this code print, and why? const e = new Error(); console.log(Object.hasOwn(e, 'message'), e.message === '', String(e));
Show answer
It prints false true Error. With no argument, the constructor creates no own message property, so e.message comes from Error.prototype.message, which is ''. toString() returns only the name when the message is empty, so the result is 'Error'.
Exercise
A logging function does logger.info(JSON.stringify({ event: 'failed', error: err })) and the log shows "error":{}. Explain the cause and give a one-line fix that keeps the name, message, and stack.
Show answer
JSON.stringify serializes only enumerable own properties. message and stack are non-enumerable own properties and name is inherited, so nothing is written. One fix is error: { name: err.name, message: err.message, stack: err.stack }, which copies the values into a plain object with enumerable properties.
Exercise
You create an error in a factory function makeNotFound() and throw it from handleRequest(). Which function appears at the top of the stack trace, and does this behavior come from the ECMAScript standard?
Show answer
makeNotFound() appears at the top, because engines capture the stack when the error is constructed. This is not standardized behavior: stack is not part of ECMAScript, but every major engine captures it at construction time.