Error Handling (Node.js)

Error handling in Node.js spans several styles: error-first callbacks, try/catch around await, .catch() on Promises, and 'error' events on emitters. Unhandled errors can crash the process, so each async path needs coverage.

Node.js

Because Node is asynchronous, errors arrive through different channels and each needs its own handling. Synchronous code uses try/catch. Callback APIs use the error-first convention — check the err argument first. Promises reject, handled with .catch() or, with async/await, a try/catch around the await.

A critical detail: a try/catch will NOT catch an error thrown later inside an asynchronous callback, because by then the try block has already finished. This is a classic bug — you must handle the error where the async operation actually completes, not where you started it.

EventEmitters (and streams) emit 'error' events; an emitted 'error' with no listener throws and can crash the process, so always attach an 'error' handler. As a last resort, process.on('uncaughtException') and process.on('unhandledRejection') catch what slips through, but they are for logging and graceful shutdown — not normal control flow. In Express, pass errors to next(err) so error-handling middleware can respond.

Syntax

try { await op(); } catch (err) { ... }

Examples

JavaScript

// async/await
async function load() {
  try {
    const data = await fetchData();
    return data;
  } catch (err) {
    console.error("load failed:", err.message);
    throw err;
  }
}

// always handle emitter errors
stream.on("error", err => console.error(err));

Learn it in a lesson

See also

Back to the Dictionary