Sub topic 8
Error-First Callbacks in Node.js
This chapter assumes you can write and pass callbacks. It also assumes you know that asynchronous callbacks run later, after the current code finishes. You should be able to run a script with Node.js. Here you will learn the convention Node.js uses to report failures through callbacks, and the mistakes people make when they apply it.
Why Asynchronous Code Needs a Convention for Errors
try/catch only catches errors thrown while the try block is still on the call stack. An asynchronous operation such as reading a file finishes after your function has already returned. By the time the failure happens, there is no surrounding try block left to catch it.
const fs = require('node:fs');
try {
fs.readFile('missing.json', 'utf8', (err, data) => {
// The failure arrives here, long after the try block has finished
});
} catch (e) {
console.log('This never runs for a missing file');
}So the error has to be delivered the same way the result is: as an argument to the callback.
The Convention
Node.js core APIs follow one rule. The first argument of the callback is the error. Any results come after it.
- If the operation failed,
erris anErrorobject and the results are usuallyundefined. - If it succeeded,
errisnulland the results follow.
const fs = require('node:fs');
fs.readFile('config.json', 'utf8', (err, data) => {
if (err) {
console.error('Read failed:', err.message);
return;
}
console.log('Read', data.length, 'characters');
});The return inside the if block matters. Without it, the code goes on to use data even though the read failed.
Writing Your Own Error-First Function
When you write a function that takes a callback, follow the same contract so callers can treat it like any core API.
function divideLater(a, b, callback) {
setTimeout(() => {
if (b === 0) {
callback(new Error('Division by zero'));
return;
}
callback(null, a / b);
}, 10);
}
divideLater(10, 2, (err, result) => {
if (err) return console.error(err.message);
console.log('Result:', result); // Result: 5
});
divideLater(1, 0, (err, result) => {
if (err) return console.error(err.message); // Division by zero
console.log('Result:', result);
});Two details are worth copying:
- Pass a real
Errorobject, not a string. AnErrorcarries a stack trace and amessage, and callers can checkerr.codeorinstanceof. - Pass
nullexplicitly on success. Callers testif (err), so any falsy value works, butnullis what Node.js uses and what readers expect.
Common Errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Forgetting `return` after handling `err` | Code runs on `undefined` results and may crash | `if (err) return callback(err);` |
| Ignoring `err` entirely | Failures are silent | Always check the first argument |
| Throwing inside the async callback | The throw escapes to the process and becomes an uncaught exception | Pass the error to the callback instead |
| Calling the callback twice | The caller's logic runs twice, once with an error and once with a result | Return right after every `callback(...)` call |
| Putting the result first | Callers read the result as an error | Keep the error in position one |
Forwarding Errors
A function that calls another error-first function usually forwards the error instead of handling it. The if (err) return callback(err); line passes the failure up to whoever called you. That line shows up constantly in callback-based Node.js code. Its repetition is one reason the later chapters on flattening callbacks and Promises exist.
Exercise
This function sometimes logs "Parsed: undefined" and then crashes. Find both bugs. function loadJson(path, callback) { fs.readFile(path, 'utf8', (err, text) => { if (err) callback(err); callback(null, JSON.parse(text)); }); }
Show answer
First, there is no return after callback(err), so on a read failure the function keeps going. It calls JSON.parse(undefined), and the callback can run twice. Second, JSON.parse can throw inside the async callback, which becomes an uncaught exception. Fix both: write if (err) return callback(err); then wrap JSON.parse in try/catch, call return callback(parseErr) in the catch, and call callback(null, value) after the try/catch.
Exercise
Why does Node.js deliver errors as a callback argument instead of throwing them from fs.readFile?
Show answer
The read finishes after fs.readFile has returned and its caller's stack frames are gone. No try/catch around the call could catch a later throw, so the error has to travel the same way as the result: through the callback.