skip to content

Error Conventions and Propagation

Node's two error styles, error-first callbacks and rejected promises, and carrying a useful error between them. Asked about operational vs programmer errors: retry, 4xx or crash.

on this pageshow

explore

questions

5

In Node.js, how does the error-first callback convention work, and what rules must a callback-style API and its caller follow?

level: juniorimportance: must knowfreq 70%

answer

  1. what the first parameter is for
  2. the value of err on success
  3. early return after handling
  4. called once, never synchronously
  5. try/catch cannot reach it

basics

~20 s

A Node.js callback API calls its last argument as callback(err, result): err is an Error on failure and null on success. The caller checks err first and returns; the API calls back exactly once, always asynchronously.

solid answer

~40 s

Node's callback APIs such as `fs.readFile` take a callback as the last argument and invoke it as `callback(err, value)`. On failure `err` is an `Error`, usually carrying a `code` such as `ENOENT`; on success it is `null` and the result follows. The caller tests `if (err)` first, handles it and returns, so the success path never runs with bad data. The API has two duties: call the callback exactly once, and never call it synchronously on some paths and asynchronously on others; the official event-loop guide defers early errors with `process.nextTick(callback, err)`. Because the result arrives after the calling function has returned, a `try/catch` around the call cannot see the I/O error, and anything the callback itself throws escapes as an uncaught exception rather than coming back as `err`.

code

javascript · 31 lines
javascript
import { readFile } from 'node:fs';

function loadManifest(path, callback) {
  if (typeof path !== 'string') {
    // Report early errors asynchronously so the API is never sync on one path.
    process.nextTick(callback, new TypeError('path must be a string'));
    return;
  }
  readFile(path, 'utf8', (err, text) => {
    if (err) {
      callback(err); // ENOENT, EACCES, ... passed up unchanged
      return;
    }
    let manifest;
    try {
      manifest = JSON.parse(text);
    } catch (parseErr) {
      callback(parseErr);
      return;
    }
    callback(null, manifest); // outside the try: a throwing caller cannot trigger a second call
  });
}

loadManifest('./manifest.json', (err, manifest) => {
  if (err) {
    console.error('manifest not loaded:', err.code ?? err.message);
    return;
  }
  console.log(Object.keys(manifest));
});

go deeper

for a junior

Recall the signature callback(err, value), that err is null on success, and the habit of checking err first and returning straight after handling it.

for a middle

Explain why try/catch around a callback call misses I/O errors, and the API author's duties: call back exactly once and never synchronously on some paths.

for a senior

Show the subtle bugs: a success callback invoked inside the API's own try, a cache hit that calls back synchronously, and errors flattened to strings that lose their code.

for a principal

Weigh where a codebase still exposes callback APIs, how its wrappers keep the contract, and whether new modules should offer promises only.

## The shape of the convention Node.js grew up on **callback APIs**: you pass a function as the **last argument**, and Node calls it when the work finishes. The **error-first** convention fixes the order of that function's parameters: `callback(err, value)`. - On **failure**, `err` is an `Error` object. For operating-system failures it carries a string `code` such as `ENOENT` or `EACCES`, plus fields like `syscall` and `path`. - On **success**, the first argument is `null` and the result, if there is one, comes second. - The caller therefore tests `if (err)` **before** touching the result, handles the failure and **returns**, so the success path never runs with missing data. The official Node.js guide to asynchronous callbacks states it plainly: the first parameter in any callback is the error object, and if there is no error it is `null`. ## Four ways a Node API reports an error The callback is only one of the channels. Node's errors documentation lists how each API style reports failure, and you have to know which one you are calling: | API style | Example | How the error reaches you | |---|---|---| | Synchronous | `fs.readFileSync` | `throw`, caught by `try...catch` | | Callback | `fs.readFile` | the `err` argument of the callback | | Promise | `fs/promises` `readFile` | a rejected promise, caught with `await` in `try` or `.catch()` | | Event emitter | a `net.Socket`, a stream | an `'error'` event; with no listener it is thrown and crashes the process | The docs also warn that a handful of normally asynchronous methods still throw, so the per-method documentation is the final word. ## Rules for the caller - **Check `err` first, then return.** Forgetting the `return` runs the success code with `undefined` data. - **Do not wrap the call in `try...catch` to catch I/O failures.** The `try` block has already exited by the time the callback runs, so only synchronous throws, such as argument validation, are caught there. - **Do not throw from inside the callback and expect it to come back as `err`.** A throw there unwinds into Node's internals and surfaces as an uncaught exception, which by default ends the process. - **Pass the error on unchanged** when you cannot handle it, so its `code` survives for whoever can. ## Rules for the API author 1. **Call the callback exactly once.** Success and failure are mutually exclusive. Node's internals use the code `ERR_MULTIPLE_CALLBACK`, "a callback was called more than once", for the same violation. 2. **Be consistently asynchronous.** An API that calls back synchronously on one path (a cache hit, an early validation failure) and asynchronously on another makes the caller's code run in an order that depends on the data. The Node.js event-loop guide shows the fix: report early errors with `process.nextTick(callback, err)`, so the callback runs after the caller's code but before the event loop moves on. 3. **Never call the success callback inside the `try` that guards your own work.** If the caller's callback throws, your `catch` receives the caller's exception and calls back a second time with it. Compute inside `try`, call back outside it. 4. **Pass an `Error`, not a string.** Callers read `err.code` and `err.stack`; a string has neither. ## Node core's own split Node core itself does not defer everything. Its callback APIs validate arguments **before** starting any work and **throw synchronously** on a programmer mistake: `fs.open({}, cb)` throws `TypeError [ERR_INVALID_ARG_TYPE]` at once. Operational failures that come from the operating system, such as a missing file, always arrive through the callback. So the guide's `nextTick` pattern is for errors your API chooses to report through the callback; argument checks that throw immediately are an equally valid, and common, design. ## Bridging the two styles Modern code mixes callbacks and promises. `util.promisify` turns an error-first function into one returning a promise, and `util.callbackify` goes the other way, delivering a rejection as `err` (or `null` on success). How to write those wrappers by hand is covered in the JavaScript lesson on promisification; what matters here is that both rely on every callback API keeping this convention. One edge shows why `null` is special. Because a `null` first argument means success, `util.callbackify` cannot pass a falsy rejection reason through as-is: if the promise rejects with `null`, `0` or `''`, Node wraps that value in an `Error` with code `ERR_FALSY_VALUE_REJECTION` and keeps the original in a `reason` property. The convention depends on every real failure being a truthy value, ideally an `Error`.

  • Why should a callback-style API not call callback(null, result) inside the try block that guards its own parsing?
    If the caller's callback throws, that `catch` receives the caller's exception and calls `callback(err)`, so the callback runs twice: once with success, then with an error that is not the API's. Compute inside `try`, call back outside it. Node's internals report the same bug class as `ERR_MULTIPLE_CALLBACK`.
  • Node core throws a TypeError synchronously when fs.open is given an object as its path. Doesn't that break the always-asynchronous rule?
    Node separates the two cases. Invalid arguments are programmer mistakes, checked before any work starts and thrown at once as `TypeError` with codes like `ERR_INVALID_ARG_TYPE`. Failures from the operating system, such as `ENOENT`, always arrive through the callback. The rule is about errors an API chooses to deliver through its callback: those must never be delivered synchronously.

  • Wrapping fs.readFile in try/catch will catch a missing-file error.
  • On success err is an empty Error, so check err.message instead.
  • Calling back synchronously on a cache hit is a harmless optimisation.
  • An exception thrown inside the callback comes back as its err argument.
  • After handling err there is no need to return; the rest is skipped.
open as a page

In a Node.js service, what separates an operational error from a programmer error, and which one calls for a retry, a client-error response, or a crash?

level: middleimportance: must knowfreq 55%

basics

~20 s

In Node.js, an operational error is a failure correct code must expect, such as ENOENT or ECONNRESET; a programmer error is a bug, such as ERR_INVALID_ARG_TYPE. Retry transient operational errors, report permanent ones, and never retry bugs.

open as a page

In Node.js, what does a system error such as ENOENT or ECONNRESET carry, and why should code branch on error.code rather than error.message?

level: middleimportance: must knowfreq 60%

basics

~20 s

A Node.js system error is a plain Error with a string code such as ENOENT, a negative platform-specific errno, the failing syscall, and a path or address when relevant. Node documents code as stable; message text may change in any release.

open as a page

A Node.js 24 client's net.connect to localhost on a closed port fails with an AggregateError rather than one ECONNREFUSED; why, and how should retry and logging code read it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Since Node 20, net.connect defaults to autoSelectFamily: true and tries every resolved address in turn. When all attempts fail it emits one AggregateError whose errors array holds each attempt, with the first attempt's code copied onto it.

open as a page

In a Node.js module that wraps low-level failures such as ENOENT or ECONNRESET in its own errors, how do you keep them matchable by code and still diagnosable?

level: seniorimportance: should knowfreq 40%

basics

~20 s

In Node.js, throw an Error subclass with a stable code of your own and pass the original as cause. Callers match on code, util.inspect prints the cause chain, and retry logic walks cause, as it must for fetch's 'fetch failed'.

open as a page