← Back to Node.js, page 2

nodejs-0027 · Easy fresher

What are error-first callbacks, and why does try/catch not catch errors from asynchronous callbacks?

An error-first callback receives (err, result), and err is null on success. try/catch only catches errors thrown while its block is running on the call stack. An async callback runs later on a new stack, after the try block has ended, so the error must be passed through the callback, a promise or an event.

Full answer

Node's older APIs follow one convention: the callback is the last argument, and its first parameter is an error. If the operation worked, err is null or undefined, and the result follows. The first line of every callback should be the error check, and the function should return after handling it.

try/catch works with the call stack. When the engine runs the try block, any exception thrown during that block, directly or through functions it calls, is caught. fs.readFile(path, cb) only starts the work and returns. The try block ends. Later, the event loop calls cb on a new, empty stack. An exception thrown there has no surrounding try, so it becomes an uncaught exception and ends the process.

That is why Node APIs report operational errors (missing file, closed socket) through the callback, a rejected promise, or an 'error' event, and keep throw for programmer mistakes such as wrong argument types.

How to move to promises: util.promisify(fs.readFile) wraps a callback function that follows the convention, and the fs/promises module already returns promises. With await, try/catch works again, because await resumes the function on a stack where the try block is still active.

javascript
const fs = require('node:fs');
const { promisify } = require('node:util');

// 1. try/catch does not see the failure, the callback does.
try {
  fs.readFile('/no/such/file.txt', (err, data) => {
    if (err) {
      console.log('3. callback received the error:', err.code);
      return; // stop here, do not use data
    }
    console.log(data.length);
  });
  console.log('1. try block finished normally');
} catch (err) {
  console.log('never printed:', err.code);
}
console.log('2. code after try/catch');

// 2. With promises and await, try/catch works again.
const readFile = promisify(fs.readFile);
(async () => {
  try {
    await readFile('/no/such/file.txt');
  } catch (err) {
    console.log('4. await + try/catch caught:', err.code);
  }
})();

The numbers show the order: the try block ends long before the callback runs. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. try block finished normally 2. code after try/catch 3. callback received the error: ENOENT 4. await + try/catch caught: ENOENT

Key points

  • Error-first: callback(err, result), check err first and return.
  • try/catch covers only synchronous code on the current stack.
  • Operational errors travel by callback, rejection or 'error' event.
  • promisify or fs/promises with await gives back try/catch.

Common mistakes

  • Wrapping an asynchronous call in try/catch and expecting it to catch the callback error.
  • Calling the callback twice, once with an error and once with a result.
  • Forgetting return after handling err, so the code continues with undefined data.
  • Throwing inside a callback instead of passing the error on.

Follow-ups

  • What does util.promisify need from a function to work?
  • How do events report errors?
  • What is the difference between an operational error and a programmer error?

Tips

  • Draw two stacks to explain why the catch is skipped.
  • Say 'return after handling the error' when you mention callbacks.
  • Mention promisify as the bridge to modern code.