Error handling in Node
Overview
In a browser, an unhandled error usually breaks one feature on one person’s screen. On a server, an unhandled error can crash the process and take down the app for every user. Node programs also handle errors from three different sources — promises, callbacks and events — so it’s worth being deliberate about them.
Three styles, three techniques
Promises and async/await
Most modern Node APIs return promises. Handle their errors with try…catch around await:
import { readFile } from 'node:fs/promises';
try {
const text = await readFile('settings.json', 'utf8');
console.log(JSON.parse(text));
} catch (err) {
console.error('Could not load settings:', err.message);
}A promise that rejects with no handler triggers an unhandledRejection, which by default crashes the process. Never start a promise without either awaiting it or attaching .catch().
Error-first callbacks
Older APIs (and the callback versions of fs, crypto etc.) pass the error as the first argument:
import { readFile } from 'node:fs';
readFile('settings.json', 'utf8', (err, text) => {
if (err) {
console.error('Could not load settings:', err.message);
return; // don't carry on with undefined data!
}
console.log(JSON.parse(text));
});try…catch around readFile(…) would not catch this error — the callback runs later, after the try block has finished. Prefer the promise versions (node:fs/promises), or convert callback APIs with util.promisify.
EventEmitters
Streams, sockets and servers report errors as 'error' events. With no listener, the error is thrown and crashes the process:
const stream = createReadStream('missing.txt');
stream.on('error', (err) => console.error('Stream failed:', err.code));Error codes
Errors from Node’s APIs have a code property that tells you what kind of failure happened. Branch on it rather than on the message text, which can change between versions:
| Code | Meaning |
|---|---|
ENOENT |
no such file or directory |
EACCES / EPERM |
permission denied |
EEXIST |
file already exists |
EADDRINUSE |
the port is already in use |
ECONNREFUSED |
nothing is listening at that address |
ECONNRESET |
the other side closed the connection |
ETIMEDOUT |
the operation timed out |
try {
await mkdir('uploads');
} catch (err) {
if (err.code !== 'EEXIST') throw err; // "already exists" is fine; anything else isn't
}Two kinds of error
Operational errors are problems a correct program still has to deal with: a user sends invalid data, a file is missing, the database is briefly unreachable, an external API times out. Handle these: validate input, retry, fall back, or return a clear error response.
Programmer errors are bugs: reading a property of undefined, passing the wrong type, a typo in a function name. You can’t sensibly “handle” these at runtime — the fix is to change the code. Log them with as much detail as possible so you can.
This distinction guides where you put try…catch. Catch operational errors close to where you can respond to them. Let programmer errors travel up to a top-level handler that logs them.
Adding context
A raw ENOENT deep in a stack trace doesn’t say which feature failed. Wrap errors with context as they travel up, keeping the original as the cause:
async function loadInvoice(id) {
try {
return JSON.parse(await readFile(`invoices/${id}.json`, 'utf8'));
} catch (err) {
throw new Error(`Failed to load invoice ${id}`, { cause: err });
}
}Node prints both errors, so you see what your app was doing and the low-level reason.
The last line of defence
Node emits two process-wide events for errors that nothing caught:
process.on('unhandledRejection', (reason) => {
console.error('Unhandled promise rejection:', reason);
process.exit(1);
});
process.on('uncaughtException', (err) => {
console.error('Uncaught exception:', err);
process.exit(1);
});Why exit rather than carry on? An uncaught exception means your program was interrupted halfway through something — a half-updated object, an open file, a request never answered. Its state can no longer be trusted. The safe response is to log the error, exit, and let a process manager start a fresh copy. Docker, Kubernetes, systemd and hosting platforms all restart crashed processes automatically.
These handlers are for logging and clean exits only — never use them to keep a broken process running.
Timeouts and cancellation
A request that never finishes is a silent error. Many Node APIs accept an AbortSignal, which you can use to give up after a time limit:
try {
const res = await fetch('https://api.example.com/rates', {
signal: AbortSignal.timeout(3000),
});
} catch (err) {
if (err.name === 'TimeoutError') {
console.error('Rates service took too long');
} else {
throw err;
}
}Checklist
- Every
awaiteither sits in atryblock or is inside a function whose caller handles errors. - Every emitter you create or receive (streams, sockets, child processes) has an
'error'listener — or is used withpipeline(), which handles it for you. - You branch on
err.code, not on message text. - Low-level errors are wrapped with context using
cause. - Uncaught errors are logged and the process exits cleanly.
In an Express app, most of this is centralised in error-handling middleware — you’ll build that in Error handling in Express.
Read a config file safely
Write loadSettings(path) that returns the parsed JSON settings. If the file doesn't exist, return {}. If the JSON is invalid, throw an error that says which file is broken and keeps the original error as its cause. Any other error should be re-thrown unchanged.
import { readFile } from 'node:fs/promises';
export async function loadSettings(path) {
// your code here
}import { readFile } from 'node:fs/promises';
export async function loadSettings(path) {
let text;
try {
text = await readFile(path, 'utf8');
} catch (err) {
if (err.code === 'ENOENT') return {};
throw err;
}
try {
return JSON.parse(text);
} catch (err) {
throw new Error(`Settings file ${path} is not valid JSON`, { cause: err });
}
}Summary
- Await promises inside
try…catch; checkerrfirst in error-first callbacks; listen for'error'on emitters. - Node errors carry a
codesuch asENOENTorECONNREFUSED— branch on it, not on the message. - Operational errors are expected and handled; programmer errors are bugs to fix.
- Wrap low-level errors with context using
{ cause }. - On
uncaughtExceptionorunhandledRejection: log, then exit and let a process manager restart you.