Error handling in Node

Topic 5 of 5 in The Node runtime7 min readIntermediateFree course

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:

JavaScript
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:

JavaScript
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:

JavaScript
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
JavaScript
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 expected in a working program — file not found, network timeout, invalid user input, database down — and are handled with retries, fallbacks or 4xx/5xx responses. Programmer errors are bugs — undefined is not a function, wrong argument types, typos — and are fixed in the code; log them and restart.

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:

JavaScript
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:

JavaScript
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:

JavaScript
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 await either sits in a try block 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 with pipeline(), 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.

Exercise

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.

JavaScript
import { readFile } from 'node:fs/promises';

export async function loadSettings(path) {
  // your code here
}

Summary

  • Await promises inside try…catch; check err first in error-first callbacks; listen for 'error' on emitters.
  • Node errors carry a code such as ENOENT or ECONNREFUSED — 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 uncaughtException or unhandledRejection: log, then exit and let a process manager restart you.