Sub topic 8
Error-First Callbacks in Node.js
This chapter assumes you know how asynchronous callbacks work with setTimeout and I/O, and that you can run a script with Node.js. It covers the convention Node.js uses to report failures from asynchronous operations, how to write functions that follow it, and the mistakes that most often break it.
Why Asynchronous Errors Need a Convention
In synchronous code you handle a failure with try/catch. That works because the failing call runs while the try block is still on the call stack. An asynchronous callback runs later, after the code that started the operation has finished and its stack frames are gone. A try block around the starting call cannot catch a failure that happens after it has already exited.
const fs = require('node:fs');
try {
fs.readFile('missing.json', 'utf8', (err, data) => {
if (err) {
console.log('The callback received:', err.code);
return;
}
console.log(data);
});
console.log('readFile returned without throwing');
} catch (e) {
console.log('This line never runs for a missing file');
}
// readFile returned without throwing
// The callback received: ENOENTThe file read fails long after the try block has finished. Throwing at that point would have nothing to catch it. Node.js therefore hands the error to the callback as an ordinary argument instead of throwing it.
The Shape of an Error-First Callback
The convention has a few rules:
- The callback is the last argument of the asynchronous function.
- The callback's first parameter is the error. On failure it is an
Errorobject. On success it isnull. - Any results come after the error:
(err, result), or(err, result1, result2)when there is more than one. - The callback is called exactly once.
Some Node.js APIs return several results. fs.read calls back with (err, bytesRead, buffer). The error always stays in the first position.
Checking the error correctly
Test the error with if (err), not if (err !== null). Node.js core passes null on success, but many third-party libraries pass undefined or leave the argument out. A truthiness check handles every one of those cases.
Return as soon as you have handled the error. If you leave out the return, execution falls through to the success path, where data is undefined. That usually causes a second and more confusing error.
const fs = require('node:fs');
fs.readFile('missing.json', 'utf8', (err, data) => {
if (err) {
console.error('Read failed:', err.message);
// missing return: execution continues below
}
console.log(data.length); // TypeError: Cannot read properties of undefined
});What Is Inside the Error Object
Node.js system errors carry more than a message. The properties let you react to particular failures instead of treating them all alike.
| Property | Example value | Meaning |
|---|---|---|
| `code` | `'ENOENT'` | A stable string that names the failure |
| `errno` | `-2` | The numeric error number from the operating system |
| `syscall` | `'open'` | The system call that failed |
| `path` | `'missing.json'` | The file path involved, for file system errors |
| `message` | `"ENOENT: no such file or directory, open 'missing.json'"` | A human-readable description |
Branch on err.code, never on err.message. Message text can change between Node.js versions, but codes are part of the documented API. Some common file system codes:
| Code | Typical cause |
|---|---|
| `ENOENT` | The file or directory does not exist |
| `EACCES` | Permission denied |
| `EISDIR` | You tried to read a directory as a file |
| `EMFILE` | The process has too many open files |
const fs = require('node:fs');
fs.readFile('settings.json', 'utf8', (err, text) => {
if (err && err.code === 'ENOENT') {
console.log('No settings file, using defaults');
return;
}
if (err) {
console.error('Unexpected failure:', err.code, err.message);
return;
}
console.log('Loaded', text.length, 'characters');
});A missing file here is an expected situation with a fallback. Anything else is reported as a real error.
Writing Your Own Error-First Function
When your function wraps another error-first call, it has three jobs:
- forward errors from the inner operation to its own callback,
- turn synchronous exceptions, such as a
JSON.parsefailure, into callback errors, - call its callback exactly once.
const fs = require('node:fs');
function readJson(path, callback) {
fs.readFile(path, 'utf8', (err, text) => {
if (err) return callback(err);
let value;
try {
value = JSON.parse(text);
} catch (parseErr) {
return callback(parseErr);
}
callback(null, value);
});
}
fs.writeFileSync('good.json', '{"port": 8080}');
fs.writeFileSync('bad.json', '{port: 8080}');
readJson('good.json', (err, config) => {
if (err) return console.error('good.json:', err.message);
console.log('good.json port:', config.port);
});
readJson('bad.json', (err) => {
if (err) console.error('bad.json:', err.name);
});
readJson('nope.json', (err) => {
if (err) console.error('nope.json:', err.code);
});Running this logs a port of 8080 for good.json, a SyntaxError for bad.json, and ENOENT for nope.json. The three lines can appear in any order because the reads finish independently.
The return callback(err) idiom calls the callback and leaves the function in one statement. The return value itself does not matter. The return is there to stop execution.
Keep the callback call outside the try block
This version looks equivalent, but it has a bug:
function readJsonBuggy(text, callback) {
try {
const value = JSON.parse(text);
callback(null, value); // if this throws...
} catch (e) {
callback(e); // ...the callback runs a second time
}
}
readJsonBuggy('{"a": 1}', (err, value) => {
console.log('callback called with err =', err && err.message);
if (!err) throw new Error('bug in caller');
});
// callback called with err = undefined
// callback called with err = bug in callerIf the caller's callback throws, the catch block catches the caller's own exception and calls the callback a second time with it. The caller now gets success and failure for the same operation. Put only the code that can fail inside try, then call the callback after the try/catch, as readJson does.
Add context when you forward errors
A bare ENOENT from deep inside a library gives no hint about what the program was trying to do. Wrap the error and keep the original as its cause (supported since Node.js 16.9):
const fs = require('node:fs');
function loadUserProfile(userId, callback) {
const path = `profiles/${userId}.json`;
fs.readFile(path, 'utf8', (err, text) => {
if (err) {
return callback(
new Error(`Could not load profile for user ${userId}`, { cause: err })
);
}
callback(null, text);
});
}
loadUserProfile(42, (err) => {
if (err) {
console.error(err.message); // Could not load profile for user 42
console.error(err.cause.code); // ENOENT
}
});Throwing Inside a Callback Crashes the Process
A throw inside an asynchronous callback has no try block above it on the stack. Node.js treats it as an uncaught exception, prints the stack trace, and exits the process with a non-zero code.
const fs = require('node:fs');
fs.readFile('missing.json', 'utf8', (err, data) => {
if (err) throw err; // terminates the whole process
console.log(data);
});if (err) throw err is fine in a throwaway script where crashing is what you want. In a server it takes down every request in progress, not only the one that failed. Inside library and application code, forward the error to a callback or handle it where you are.
Errors That Arrive Through the Wrong Channel
An error-first function should report every failure through its callback. When it also throws synchronously for some inputs, every caller needs both try/catch and an err check. Node.js core makes one deliberate exception: it throws right away for programmer errors, such as passing a number where a callback function is required, because these are bugs to fix and not runtime conditions to handle.
| Kind of failure | Example | How it is reported |
|---|---|---|
| Operational error | File missing, network down, invalid JSON from disk | Passed as `err` to the callback |
| Programmer error | Callback argument is not a function | Thrown synchronously, before any I/O starts |
Follow the same split in your own functions. Validate arguments up front and throw a TypeError for misuse. Report everything that can go wrong during the operation through the callback.
A related problem is timing. If a function sometimes calls back synchronously, for example on a cached result or on a validation failure, and sometimes asynchronously, callers see a different execution order on each path. The chapter on inversion of control covers how to keep a function consistently asynchronous.
Common Mistakes at a Glance
| Mistake | Symptom | Fix |
|---|---|---|
| No `return` after handling `err` | A second error on the success path | `if (err) return callback(err);` |
| `if (err !== null)` | Success treated as failure when a library passes `undefined` | `if (err)` |
| Calling the callback inside `try` | Callback runs twice when the caller throws | Call it after the `try`/`catch` |
| `throw` inside an async callback | Process exits | Forward the error to the callback |
| Ignoring `err` entirely | `undefined` results and confusing errors later | Check `err` first, every time |
| Passing strings as errors | No stack trace, no `code` | Pass `Error` instances |
Exercise
The function below sometimes calls its callback twice. Find the cause and rewrite the function so the callback is called exactly once on every path. function getSize(path, callback) { fs.stat(path, (err, stats) => { if (err) callback(err); callback(null, stats.size); }); }
Show answer
When fs.stat fails, the function calls callback(err) and then keeps going to callback(null, stats.size). Because stats is undefined, that line throws a TypeError inside an asynchronous callback, which crashes the process (or, if stats were defined, the callback would run a second time). Return after forwarding the error: function getSize(path, callback) { fs.stat(path, (err, stats) => { if (err) return callback(err); callback(null, stats.size); }); }
Exercise
Write readPort(path, callback). It reads a JSON file and calls back with the file's numeric "port" property. If the file does not exist (ENOENT), call back with the default port 3000 and no error. If the JSON is invalid or "port" is not a number, call back with an Error. Every other read error should be forwarded unchanged.
Show answer
One correct solution:
const fs = require('node:fs');
function readPort(path, callback) {
fs.readFile(path, 'utf8', (err, text) => {
if (err && err.code === 'ENOENT') return callback(null, 3000);
if (err) return callback(err);
let config;
try {
config = JSON.parse(text);
} catch (parseErr) {
return callback(parseErr);
}
if (typeof config.port !== 'number') {
return callback(new Error(${path}: "port" must be a number));
}
callback(null, config.port);
});
}
The ENOENT check comes before the general error check, JSON.parse is the only code inside the try block, and every branch either returns right after calling the callback or calls it as the last statement.
Exercise
A teammate writes if (err) throw err; inside the fs.readFile callback of an HTTP request handler and wraps the fs.readFile call in try/catch "to be safe." Explain what happens when the file is missing and what they should do instead.
Show answer
The try/catch has already exited by the time the callback runs, so it catches nothing. The throw becomes an uncaught exception and the Node.js process exits, dropping every request in progress. Instead, handle the error inside the callback, for example by sending a 404 or 500 response and returning, or by forwarding it to the next error-first callback.