Sub topic 1
What an Error Is: name, message, and stack
When JavaScript code fails, the engine reports the problem with an Error object. Your own code can create the same kind of object. Before you can throw or catch errors, you need to know what an error looks like and what information it gives you. This chapter covers that.
Prerequisites
This chapter assumes you can:
- Write JavaScript variables, functions, and control flow such as
ifand loops. - Read object property access and the basic
classsyntax. - Run a script in the browser console or with Node.js (
node file.js).
Creating an Error Object
An Error object is an ordinary JavaScript object made by the Error constructor. Creating one does not stop your program. It is just a value until you throw it, which the next chapter covers.
const err = new Error('Disk is full');
console.log(typeof err); // 'object'
console.log(err instanceof Error); // true
console.log(err.name); // 'Error'
console.log(err.message); // 'Disk is full'
console.log(String(err)); // 'Error: Disk is full'Calling Error('Disk is full') without new also returns a new Error object. Most codebases use new anyway because it is clearer.
The Three Properties You Will Use
| Property | What it holds | Standardized? |
|---|---|---|
| `name` | The error's type, such as `'Error'` or `'TypeError'` | Yes |
| `message` | The human-readable description you passed in | Yes |
| `stack` | A text trace of where the error was created | No, but supported by all major engines |
name and message together produce the default string form, "name: message". That string is what you see when you call String(err) or err.toString().
Reading the stack
The stack property records the chain of function calls that was active when the error was created. The point where it gets thrown does not matter. That makes it the most useful property when debugging.
function loadSettings() {
return readFile();
}
function readFile() {
return new Error('File not found');
}
const err = loadSettings();
console.log(err.stack);In Node.js the output looks roughly like this:
Error: File not found
at readFile (/home/me/stack.js:6:10)
at loadSettings (/home/me/stack.js:2:10)
at Object.<anonymous> (/home/me/stack.js:9:13)
...Read the trace from top to bottom. The first line is name: message. Each line after it is a stack frame, starting with the innermost call. Each frame gives the function name, the file, and the line and column.
Errors the Engine Creates
When the engine detects a problem, it builds the same kind of object for you. The example below uses try and catch to get at that object. Chapter 3 explains how they work.
try {
const user = null;
user.name;
} catch (err) {
console.log(err.name); // 'TypeError'
console.log(err.message); // e.g. "Cannot read properties of null (reading 'name')"
console.log(err instanceof Error); // true
}The name here is 'TypeError', not 'Error'. JavaScript has several built-in error types, and all of them inherit from Error. They have their own chapter later.
Common Mistakes
- Comparing messages to detect error kinds. Engines word their messages differently, and the wording changes between versions. Check
nameor useinstanceofinstead. - Logging only
err.message. You lose the stack. In logs, preferconsole.error(err), which prints the stack in both Node.js and browsers. - Assuming
new Error()stops execution. Creating an error does nothing until you throw it.
Exercise
You run const e = new Error('Timeout'); console.log(String(e), e.name); What is printed, and does the stack trace point to where e was created or where it is later thrown?
Show answer
It prints "Error: Timeout Error". The stack trace records where the Error object was created, which is the line containing new Error('Timeout'), not where it is later thrown.
Exercise
Why should code avoid checks like if (err.message.includes('Cannot read properties'))?
Show answer
Error messages are not standardized. Different engines and versions word them differently, so the check is unreliable. Checking err.name or using err instanceof TypeError is stable.