Sub topic 1
What an Error Is: name, message, and stack
Prerequisites
This chapter assumes you know JavaScript variables, functions, and control flow. It also assumes you are comfortable with objects and class syntax, and can run scripts in the browser console or Node.js.
Error Objects
An Error object describes a failure. It has three properties you will read most often:
| Property | Contains |
|---|---|
| `name` | The error type, such as `"Error"` or `"TypeError"` |
| `message` | A human-readable description |
| `stack` | The call path that led to the error (non-standard, but supported everywhere) |
const err = new Error('Disk is full');
console.log(err.name); // 'Error'
console.log(err.message); // 'Disk is full'
console.log(err.stack); // 'Error: Disk is full\n at ...'Throwing Errors on Purpose
The throw statement stops the current function and passes control up the call stack until some code catches the error. You can throw any value. Throw Error objects anyway, because only they record a stack.
function divide(a, b) {
if (b === 0) throw new Error('Cannot divide by zero');
return a / b;
}Catching Errors with try and catch
Code inside try runs normally. If it throws, the rest of try is skipped and catch receives the error.
function parseConfig(text) {
try {
return JSON.parse(text);
} catch (err) {
console.error('Invalid config:', err.message);
return {};
}
}
console.log(parseConfig('{"debug": true}')); // { debug: true }
console.log(parseConfig('not json')); // logs the error, then {}Cleaning Up with finally
A finally block runs whether try returns normally or throws. Use it for cleanup such as stopping timers or closing resources. Without a catch, the error still reaches the caller.
function withTimer(label, fn) {
console.time(label);
try {
return fn();
} finally {
console.timeEnd(label);
}
}
withTimer('work', () => 42); // logs the elapsed time, returns 42function pick() {
try {
return 'from try';
} finally {
return 'from finally';
}
}
console.log(pick()); // 'from finally'Exercise
What does withTimer('x', () => { throw new Error('fail'); }) do?
Show answer
It starts the timer, and fn throws. The finally block stops and logs the timer. The error then propagates to the caller, because there is no catch.
Exercise
Why is throw new Error('bad input') better than throw 'bad input'?
Show answer
An Error object has name, message, and stack properties, so you can see where the failure happened. A thrown string has none of these.