All academies

Error Handling

try/catch, error-first callbacks, async errors, and custom errors.

18 minLevel 16 of 20

Errors are values, and throw changes control flow

An Error is an object carrying a message, a name, and a stack trace showing where it was created. throw hurls it up the call stack until a try/catch catches it — or, if nothing does, the process crashes.

Two habits from day one:

  • Always throw Error objects, never strings — strings have no stack trace
  • Catch errors where you can actually handle them — catching just to ignore hides bugs

Node errors often carry extra properties, like the code field ("ENOENT", "ECONNREFUSED") you saw in the fs lesson.

throw, catch, inspect
function withdraw(balance, amount) {
  if (amount > balance) {
    throw new Error("Insufficient funds: have " + balance + ", want " + amount);
  }
  return balance - amount;
}

try {
  withdraw(50, 100);
} catch (err) {
  console.log("name:   ", err.name);      // Error
  console.log("message:", err.message);
  console.log("has stack trace?", typeof err.stack === "string");
}
console.log("Program continues after catching.");

Error-first callbacks

try/catch only works for synchronous code — by the time an async callback runs, the surrounding try block is long gone. Classic Node APIs use the error-first callback convention instead: every callback receives (err, result), with exactly one of them set.

  • Check err first, always — and return early
  • Never touch result before that check

You will meet this pattern throughout older code and parts of the standard library, even though promises have replaced it in new code.

The error-first convention
const fs = require("fs");

fs.readFile("/definitely/missing.txt", "utf8", (err, data) => {
  if (err) {
    console.log("Handled:", err.code); // ENOENT
    return; // do NOT fall through
  }
  console.log("File contents:", data);
});

// A try/catch around this would NOT catch the error -
// the callback runs later, on a fresh stack.
console.log("readFile scheduled...");

Errors in promises and async/await

Promises carry errors in their rejected state. Two ways to handle them:

  • .catch(handler) at the end of a chain — one handler catches a failure from any earlier step
  • try/catch around await — async/await restores the natural syntax, and it *does* work here, because await rethrows rejections

An unhandled rejection — a rejected promise with no handler — crashes modern Node with a fatal error. Every promise chain must end in a .catch, or every await must sit inside a try/catch somewhere up the chain.

try/catch works again with await
function flaky(shouldFail) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      shouldFail ? reject(new Error("network down")) : resolve("data!");
    }, 50);
  });
}

async function main() {
  try {
    console.log(await flaky(false)); // "data!"
    console.log(await flaky(true));  // throws here
  } catch (err) {
    console.log("caught async error:", err.message);
  }
}

main();

Custom error classes

Real applications distinguish error *kinds*: a validation failure should produce a 400 response, a missing record a 404, a database outage a 500. Subclassing Error lets handlers make those decisions with instanceof instead of fragile message-string matching.

Give custom errors a proper name and any structured fields handlers need (like a statusCode). This becomes the backbone of clean API error handling in the final project.

An error hierarchy
class AppError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.name = this.constructor.name;
    this.statusCode = statusCode;
  }
}
class NotFoundError extends AppError {
  constructor(what) { super(what + " not found", 404); }
}
class ValidationError extends AppError {
  constructor(msg) { super(msg, 400); }
}

try {
  throw new NotFoundError("User 42");
} catch (err) {
  if (err instanceof AppError) {
    console.log(err.name + " (" + err.statusCode + "): " + err.message);
  } else {
    throw err; // unknown errors keep bubbling up
  }
}

Operational vs programmer errors

Not all errors deserve the same treatment:

  • Operational errors — expected failures in a correctly written program: a file is missing, a request times out, user input is invalid. Handle these: retry, use a fallback, return a 4xx response.
  • Programmer errors — bugs: reading a property of undefined, passing wrong types. The program is now in an unknown state. Don't try to handle these — let the process log the error and crash, and let your process manager restart it clean.

The safety nets process.on("uncaughtException") and process.on("unhandledRejection") exist for exactly one job: log the failure, then exit. Using them to keep a corrupted process running trades a clean crash for mysterious misbehavior later.

Last-resort handlers
// Log-and-exit safety nets (register once, at startup):
process.on("uncaughtException", (err) => {
  console.error("FATAL uncaught exception:", err.message);
  process.exitCode = 1; // real apps: flush logs, then process.exit(1)
});

// Operational error - handled locally, process stays healthy:
try {
  JSON.parse("{not json");
} catch (err) {
  console.log("Handled operational error:", err.name);
}

console.log("Still running fine.");

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

Why doesn't a try/catch around fs.readFile (callback version) catch its errors?