Error Handling — Node.js

A route throws an error (throw) or calls next(err). Then one error middleware with four parameters (err, req, res, next), placed after every route, answers…

Ever opened an app and got "Something went wrong, please try again later"? That sentence is general on purpose. Meanwhile, the server writes the full error into its log (where the server records what happens), and all you get is that general sentence.

Error handling is the set of rules for what happens when something fails: the note you asked for doesn't exist, the data file is gone, the input is odd. In Express, those rules live in one place, called the error middleware. Every error gets an answer of the same shape, and the details only go to the server log.

From try/catch to one place for every error

try { ... } catch (err) { ... } catches an error thrown (throw new Error("...")) inside the try block. So the program doesn't stop halfway, and its message is in err.message. In the earlier lessons, each route answered its own 404 with return res.status(404).json({ error: "Note not found" }). The more routes, the more places that write an error answer, and their shapes can differ. Express has a tidier way: a route just throws the error, and one error middleware at the very bottom answers them all.

Error middleware: four parameters, at the very bottom

Here is the app.js of the notes-api project. Its data is read from the file data/notes.json, as in the built-in modules lesson (fs, path, os):

// Express 5: npm install express
const express = require("express");
const fs = require("node:fs/promises");
const path = require("node:path");

const app = express();

function httpError(status, message) {
  const err = new Error(message);
  err.status = status;
  return err;
}

async function findNote(id) {
  const content = await fs.readFile(path.join(__dirname, "data", "notes.json"), "utf8");
  return JSON.parse(content).find((n) => n.id === id);
}

app.get("/notes/:id", async (req, res) => {
  const id = Number(req.params.id);
  if (!Number.isInteger(id)) throw httpError(400, "id must be a number");
  const note = await findNote(id);
  if (!note) throw httpError(404, "Note not found");
  res.json(note);
});

// Error middleware: after every route, with four parameters
app.use((err, req, res, next) => {
  const status = err.status || 500;
  if (status === 500) console.error(err);
  const message = status === 500 ? "Something went wrong on the server" : err.message;
  res.status(status).json({ error: message });
});

app.listen(3000, () => {
  console.log("Server running at http://localhost:3000");
});

Four requests, four answers

Request What happens Status Body
GET /notes/1 the note is found 200 {"id":1,"title":"Groceries","content":"buy 5 kg of rice"}
GET /notes/9 not found 404 {"error":"Note not found"}
GET /notes/abc Number("abc") gives NaN 400 {"error":"id must be a number"}
GET /notes/1, data file missing readFile fails: ENOENT 500 {"error":"Something went wrong on the server"}

400 means the request is wrong, 404 what was asked for isn't there, 500 (Internal Server Error) the server is at fault. For the last request in the table, the server's terminal prints the full error, including the at ... lines. Those lines are called a stack trace: the trail of which function called which until the error happened, with file names and line numbers.

Express 4 and Express 5: errors from an async handler

An async function always returns a Promise, and a throw inside it makes that Promise rejected. Express 5 waits for the Promise from the handler. When that Promise is rejected, Express 5 calls next(err) for you, so the error reaches the error middleware.

Express 4 doesn't check that Promise at all, so nothing catches the rejection. This is called an unhandled promise rejection (a rejected Promise that nothing catches). Since Node 15, an unhandled promise rejection stops the Node process:

/home/budi/notes-api/app.js:9
  const err = new Error(message);
              ^

Error: Note not found
    at httpError (/home/budi/notes-api/app.js:9:15)
    at /home/budi/notes-api/app.js:23:20 {
  status: 404
}

Node.js v24.18.0

The client that asked for the missing note gets curl: (52) Empty reply from server. Every request after it gets curl: (7) Failed to connect to localhost port 3000, because the server has stopped. So one missing note stops the server for everyone.

In Express 4, an async handler has to pass its error on to next itself:

app.get("/notes/:id", async (req, res, next) => {
  try {
    const note = await findNote(Number(req.params.id));
    if (!note) throw httpError(404, "Note not found");
    res.json(note);
  } catch (err) {
    next(err); // required in Express 4
  }
});

To avoid writing try/catch in every route, many Express 4 projects use an asyncHandler wrapper. Its point is less try/catch boilerplate (the same code, written again in every route): any rejection is passed on to next automatically.

const asyncHandler = (fn) => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

app.get("/notes/:id", asyncHandler(async (req, res) => { /* the same body */ }));

asyncHandler takes an async handler fn and returns a new handler. The new handler runs fn, and if its Promise is rejected, .catch(next) passes the error on to next.

Keep stack traces away from the client

An error middleware that writes res.status(status).json({ error: err.message, stack: err.stack }) looks helpful. But when the data file is missing, anyone who opens GET /notes/1 receives "error":"ENOENT: no such file or directory, open '/home/budi/notes-api/data/notes.json'", plus a stack trace with your code's line numbers. From that, a stranger can read the server's user name, the project folder and the data file's name. That is a free map for an attacker.

Express's built-in error handler (the one that answers when you have no error middleware) sends the stack trace in HTML as long as NODE_ENV isn't production. NODE_ENV is a setting from outside the code, which on a real server usually holds production. With NODE_ENV=production, the answer for this 500 error only says Internal Server Error. Your own error middleware above doesn't read NODE_ENV. So your code decides for itself: details to the server log, a general sentence to the client.

In the exercise: getUser with try/catch

In the exercise, you fix a plain function with no server, but the pattern is the same. The starter has a users array (Budi and Siti) and getUser(id) with a try/catch. Of the three lines it prints, the first two are already right. The third isn't: in the catch, the starter prints the fixed sentence Error 500: Something went wrong on the server. Fix three things:

  1. In the catch, print "getUser(" + id + "): Error: " + err.message and then return null.
  2. User not found: after the 404 line is printed, change return; to return null.
  3. User found: after its data is printed, add return user.

The expected output:

getUser(1): {"id":1,"name":"Budi"}
getUser(99): Error 404: User not found
getUser(abc): Error: Invalid ID

⚠️ Errors that slip through or leak out

TL;DR: A route throws an error (throw) or calls next(err). Then one error middleware with four parameters (err, req, res, next), placed after every route, answers them all with the same shape, { "error": "..." }. Use the right status: 400 bad request, 404 not found, 500 server fault. Express 5 passes errors from an async handler on to the error middleware automatically. Express 4 doesn't, so the error becomes an unhandled promise rejection (a rejected Promise that nothing catches), which stops the server. In Express 4, use try { ... } catch (err) { next(err) } or the asyncHandler wrapper. Stack traces (the trail of code lines up to the error) are for the server log only, never for the client. In a catch, print err.message to the log, not a fixed sentence.

⚡ The route just throws

Write:

const note = await findNote(id);
if (!note) throw httpError(404, "Note not found");
res.json(note);

Meaning: findNote(id) looks for the note in the data file. The route doesn't answer its own errors. When the note doesn't exist, the route throws an error made by httpError, which carries the status 404. Express passes that error on to the error middleware, a special middleware that answers every error.

⚡ One error middleware, four parameters

Write:

app.use((err, req, res, next) => {
  const status = err.status || 500;
  if (status === 500) console.error(err);
  const message = status === 500 ? "Something went wrong on the server" : err.message;
  res.status(status).json({ error: message });
});

Meaning: Express recognises error middleware by its number of parameters: four, with err first. Put it at the very bottom, after every route. err.status || 500 uses the error's status, or 500 when there is none. A 500's details go to the server log, and the client only gets a general sentence.

⚡ Express 4 and async handlers

Guess first: in Express 4, an async handler throws with no try/catch. What happens to the server?

The server stops. Express 4 doesn't check the Promise from a handler, so the error becomes an unhandled promise rejection: a rejected Promise that nothing catches. Since Node 15, Node stops when a rejection like that happens.

Meaning: Express 5 passes errors from an async handler on to the error middleware by itself. In Express 4, catch them with try { ... } catch (err) { next(err); }, or use asyncHandler, a wrapper around the handler that passes the error on to next for you.

What you will learn