Sub topic 1
What an Error Is: name, message, and stack
Every failure in JavaScript eventually reaches you as a value. Usually that value is an Error object. This chapter covers what that object contains, where its properties live, and why several obvious ways of inspecting it give misleading results. Later chapters build on this when you throw, catch, and wrap errors.
Prerequisites
This chapter assumes you already know:
- JavaScript variables, functions, and control flow
- Objects, prototypes at a basic level, and the
classsyntax - Basic promises and async/await (used in later chapters, not here)
- How to run a script in Node.js or paste code into the browser console
The examples show output from Node.js. Chrome prints the same output because it uses the same engine, V8. Firefox and Safari format stack differently, which is covered below.
Creating an Error Object
An Error object is an ordinary object created by the built-in Error constructor. You pass it a description of what went wrong:
const err = new Error('Disk quota exceeded');
console.log(err.name); // 'Error'
console.log(err.message); // 'Disk quota exceeded'
console.log(typeof err); // 'object'
console.log(err instanceof Error); // trueCalling Error without new gives the same result. Error('x') and new Error('x') both return a new Error object. Most codebases use new because it makes the intent clear.
Creating an Error object does not interrupt anything. The object is just a value. You can store it, return it, or pass it to a function, and the program keeps running. Execution only stops when you throw the value, which is the subject of the next chapter.
function makeError() {
return new Error('Created, not thrown');
}
const e = makeError();
console.log('Still running:', e.message); // Still running: Created, not thrownThe Three Properties That Matter
Error objects have three properties you will read all the time.
| Property | Type | Where it comes from | Standardized |
|---|---|---|---|
| `name` | string | Inherited from `Error.prototype` (or a subclass prototype) | Yes |
| `message` | string | Own property set by the constructor argument | Yes |
| `stack` | string | Added by the engine when the object is created | No, but every major engine supports it |
name
name identifies the kind of error. A plain Error has the name 'Error'. The engine's own errors have names such as 'TypeError' or 'RangeError':
try {
null.length;
} catch (err) {
console.log(err.name); // 'TypeError'
console.log(err.message); // "Cannot read properties of null (reading 'length')"
}The try/catch here is only a way to get hold of the error the engine creates. Chapter 3 explains it properly.
name is not stored on each error. It lives on the prototype, and each instance inherits it:
const err = new Error('x');
console.log(Object.hasOwn(err, 'name')); // false
console.log(Object.hasOwn(Error.prototype, 'name')); // true
console.log(Error.prototype.name); // 'Error'This matters when you write custom error classes later. Setting this.name in a subclass constructor creates an own property that hides the inherited one.
message
message is the human-readable description. The constructor converts its argument to a string:
console.log(new Error(42).message); // '42'
console.log(new Error({ a: 1 }).message); // '[object Object]'
console.log(new Error().message); // ''
console.log(new Error(undefined).message); // ''There is an edge case here. When you pass no argument, or pass undefined, the constructor creates no own message property at all. The empty string you read comes from Error.prototype.message:
console.log(Object.hasOwn(new Error('hi'), 'message')); // true
console.log(Object.hasOwn(new Error(), 'message')); // false
console.log(Error.prototype.message === ''); // trueYou will rarely depend on this. It does explain why code that copies only own properties sometimes loses the message, or finds none to copy.
Write the message for the developer who reads the log at 3 a.m. Say what failed and include the values that matter, for example 'Expected port between 1 and 65535, got 70000' rather than 'Invalid input'.
stack
stack is a string that holds the message followed by the chain of function calls that led to the point where the error was created:
function loadConfig() {
return readFile();
}
function readFile() {
return new Error('File not found');
}
console.log(loadConfig().stack);In Node.js this prints something like:
Error: File not found
at readFile (/home/me/stack-demo.js:6:10)
at loadConfig (/home/me/stack-demo.js:2:10)
at Object.<anonymous> (/home/me/stack-demo.js:9:13)
at Module._compile (node:internal/modules/cjs/loader:1554:14)
...The first line is name: message. Each following line is a stack frame, meaning one function call that was still active, with the most recent call first. Each frame gives the function name, file, line, and column.
How the Pieces Fit Together
Error.prototype.toString() combines the inherited and own properties. It returns name: message, or only name when the message is empty:
console.log(String(new Error('bad input'))); // 'Error: bad input'
console.log(String(new Error())); // 'Error'
console.log(`${new RangeError('too big')}`); // 'RangeError: too big'Stack Traces Across Engines
The stack property is not part of the ECMAScript standard, so its format depends on the engine.
| Engine | Used by | Example frame |
|---|---|---|
| V8 | Chrome, Edge, Node.js, Deno | ` at readFile (/app/a.js:6:10)` |
| SpiderMonkey | Firefox | `readFile@/app/a.js:6:10` |
| JavaScriptCore | Safari, Bun | `readFile@/app/a.js:6:10` |
The engines also differ in details. V8 includes the name: message line at the top of stack. Firefox does not. V8 stores stack as an own property of each instance. Firefox exposes it through an accessor on Error.prototype.
So treat stack as text for humans to read and for logging tools to store. Do not parse it with regular expressions in application code. If you need structured frames, use a library or tool designed for this, such as source-map-aware error reporting services.
V8 records only the 10 most recent frames by default. You can raise the limit while debugging deep recursion or long call chains:
Error.stackTraceLimit = 50; // V8 only; other engines ignore it
function depth(n) {
return n === 0 ? new Error('deep') : depth(n - 1);
}
console.log(depth(30).stack.split('\n').length); // about 51 linesCapturing a stack has a cost. For code that creates thousands of errors per second, such as validation in a hot loop, consider returning a plain result object instead of constructing Error objects.
Inspecting Errors Without Being Misled
The enumerable-property rules catch many developers out. message and stack are own properties, but they are non-enumerable, so the usual object tools skip them:
const err = new Error('Connection refused');
console.log(Object.keys(err)); // []
console.log(JSON.stringify(err)); // '{}'
console.log({ ...err }); // {}
console.log(Object.getOwnPropertyNames(err)); // [ 'stack', 'message' ] in V8A logger that calls JSON.stringify on an error sends {} to your log system, and you lose all of the information. Copy the properties explicitly:
function serializeError(err) {
if (!(err instanceof Error)) {
return { name: 'NonError', message: String(err) };
}
return {
name: err.name,
message: err.message,
stack: err.stack,
};
}
const err = new Error('Connection refused');
console.log(JSON.stringify(serializeError(err)));
// {"name":"Error","message":"Connection refused","stack":"Error: Connection refused\n at ..."}The instanceof check matters because JavaScript lets you throw any value, including strings and plain objects. Those values have no stack, which is one reason to always throw real Error objects. The next chapter goes into this.
console.log(err) and console.error(err) are fine for quick inspection. Node.js and browsers recognize Error objects and print the stack and any extra properties. They do not use enumeration.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `JSON.stringify(err)` for logging | Produces `'{}'` | Copy `name`, `message`, `stack` explicitly |
| `{ ...err }` to clone or extend | Loses `message` and `stack` | Build a new object from named properties |
| Parsing `err.stack` with regex | Breaks across engines and versions | Treat `stack` as opaque text |
| Comparing `err.message` to detect error kinds | Breaks when wording changes or is localized | Check `name`, `instanceof`, or a `code` property (later chapters) |
| Creating an error far from the failure | Stack points to the wrong place | Construct the error where the problem is detected |
| Vague messages like `'Error occurred'` | Logs are useless for diagnosis | Include what failed and the relevant values |
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 reads the inherited empty string from Error.prototype. toString() returns only the name when the message is empty.
Exercise
A teammate logs errors with logger.info(JSON.stringify({ event: 'save_failed', error: err })) and the log shows "error":{}. Explain the cause and rewrite the call.
Show answer
message and stack are non-enumerable, so JSON.stringify skips them and writes an empty object. Copy the fields explicitly: logger.info(JSON.stringify({ event: 'save_failed', error: { name: err.name, message: err.message, stack: err.stack } })).
Exercise
Function check() calls const failure = buildError('timeout'), and buildError does return new Error(msg). Later check() throws failure. Which function appears at the top of the stack trace, and how would you change the code so the trace starts in check()?
Show answer
buildError appears at the top, because the stack is captured when the Error object is constructed. To start the trace in check(), construct the error there with new Error('timeout'), or have buildError return only the message string.