JavaScript error handling and logging: find the bug at 2 a.m.

JavaScript error handling in a Node.js API: JSON logs with a request ID, separating sender mistakes from server errors, keeping the cause, hiding details.

Good error handling leaves a server with enough traces for the next person to find the cause. Log every request with its own ID, separate the mistakes of the sender from the errors of the server, and keep the original error. Shall we build it?

The server runs fine, but when something goes wrong it stays silent

In the previous post, I gave the order server of the Mộc café a checkpoint built with Zod, so a broken order sent from the website is stopped at the door. (Mộc is an illustrative café that I use as the running example in this series.) The owner was happy, but one thing kept bothering me: if the website sends bad data again and again at 2 a.m., who finds out in the morning? The sender gets a 400, and the server says nothing at all.

There is a second problem. When a real error happens inside the server, it only prints a stack trace. To show you how little that stack trace tells you, I set up a situation. The order list already contains one broken order, number 1050: the customer has a phone number but no name, the kind of data an old point-of-sale machine can leave behind. Then I send two requests to the server of the previous post: a bad order (the quantity is the word "two") and a request to view the list. The list function of the old server looks like this:

The list function from the previous post
function sendOrderList(response: ServerResponse, orders: Order[]): void {
  try {
    const orderListJson = JSON.stringify(listOrders(orders), null, 2);
    response.writeHead(200, JSON_HEADERS).end(orderListJson);
  } catch (error) {
    console.error(error);
    response.writeHead(500, TEXT_HEADERS).end("Server error");
  }
}

I ran the two requests, and this is everything the server left on the screen. I dropped the lines that are Node internals and kept the top, and I translated the messages from my Vietnamese run:

Output of the server from the previous post
POST bad order: 400
Error: Could not list order 1050
    at src/orders.ts:61:13
    at Array.map (<anonymous>)
    ...
  [cause]: TypeError: Cannot read properties of undefined (reading 'toUpperCase')
      at customerLabel (src/orders.ts:48:30)
GET list: 500 Server error

The two lines "POST bad order: 400" and "GET list: 500" were printed by my test script, not by the server. What the server wrote itself is only the stack trace in the middle, and it does not tell you when it happened, which request it belonged to, who called, or why the bad order was rejected (there is no line for that at all). If forty requests are interleaved at 2 a.m., that stack trace drifts among them. You can read the error, but you cannot tell which call it belongs to.

What I need is one line for every event, enough to answer four questions: what happened, when, in which request, and how serious it is.

What does a good log line look like?

I use JSON logs, one event per line. The reason is very practical: a free-text line like "Error while loading order 1050" is readable by a person, but if you want to filter "every error of request abc" or "every request slower than a second", you end up writing fragile regular expressions. With JSON every piece of information has its own name, so tools can filter by name. Every line has four fixed fields: time, level, msg (what happened) and requestId, a short code attached to exactly one request.

There are three levels, and I split them by the question "whose fault is it?":

  • info: normal things, such as an order being received.
  • warn: the caller sent something wrong. A 4xx code. The server did the right thing, someone just sent broken data.
  • error: the server did something wrong. A 5xx code. Someone needs to look.

With that split, at 2 a.m. you only need to filter error. If everything is an error, a website that sends five hundred bad orders buries the one real server error. When there are too many red alarms, nobody looks at them any more.

So that you can follow along, I rebuild the necessary parts in a new folder. The layout:

Folder layout
moc-orders/
  package.json
  src/orders.ts
  src/order-schema.ts
  src/logger.ts
  src/order-server.ts
  try-log.ts

package.json needs Node.js 22.18 or newer, because from that version Node runs .ts files directly. Run npm install to install Zod:

package.json
{
  "name": "moc-orders",
  "private": true,
  "type": "module",
  "dependencies": { "zod": "4.6.7" }
}

The file src/orders.ts describes an order and has the function listOrders, which returns the list for the admin page. Look closely at the try/catch block inside listOrders, because I come back to it later:

src/orders.ts
export type Customer = { name: string; phone: string };
export type OrderItem = { name: string; price: number; quantity: number };
export type Order = {
  id: number;
  createdAt: string;
  source: "web" | "legacy-pos";
  customer?: Customer; // a counter sale may have no customer
  items: OrderItem[];
};

export function customerLabel(order: Order): string {
  if (!order.customer) return "WALK-IN CUSTOMER";
  return order.customer.name.toUpperCase();
}

export function orderTotal(order: Order): number {
  return order.items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}

// The list for the admin page: one row per order with the ID, the customer name (in capitals) and the total.
export function listOrders(orders: Order[]) {
  return orders.map((order) => {
    try {
      return { id: order.id, customer: customerLabel(order), total: orderTotal(order) };
    } catch (error) {
      // Add context (which order) and keep the original error in cause, so the log can point at the broken order.
      throw new Error(`Could not list order ${order.id}`, { cause: error });
    }
  });
}

Prices in this post are in Vietnamese đồng, so 29,000 is about one US dollar. src/order-schema.ts is a shortened version of the Zod schema from the previous post, just enough for the server to reject an order whose quantity is a word:

src/order-schema.ts
import { z } from "zod";

// A shortened version of the schema from the previous post, enough for this one.
const itemSchema = z.strictObject({
  name: z.string().min(1),
  price: z.number().int().min(1000, "Price must be at least 1,000 VND"),
  quantity: z.number("Quantity must be a number").int().min(1),
});

export const newOrderSchema = z.strictObject({
  customer: z.strictObject({ name: z.string().min(1), phone: z.string().regex(/^0\d{9}$/) }),
  items: z.array(itemSchema).min(1),
});

// One line per problem, saying which field and what is wrong.
export function listIssues(error: z.ZodError): { field: string; problem: string }[] {
  return error.issues.map((issue) => ({ field: issue.path.join(".") || "(whole order)", problem: issue.message }));
}

Write a small logger, and the trap of the Error object

You could use a library such as Pino. I wrote a forty-line logger myself to show what it does inside, and so you understand where each log line comes from. In a real project, I think you should use an existing library instead of writing your own.

There is one detail that surprises people the first time they write a logger. Try JSON.stringify({ error: new Error("broken") }). The result is {"error":{}}, an empty object. The reason is that name, message and stack of a real error are not "enumerable" properties, so JSON.stringify skips them. The consequence is that if you log with log.error("failed", { error }), the line contains the word "failed" and an empty object. That is why I wrote the function describeError, which turns an error into plain data:

src/logger.ts
import { pathToFileURL } from "node:url";

// Write logs as JSON, one event per line. Readable by machines and by people.
export type Level = "info" | "warn" | "error";
export type Fields = Record<string, unknown>;

export type Logger = {
  info(msg: string, fields?: Fields): void;
  warn(msg: string, fields?: Fields): void;
  error(msg: string, fields?: Fields): void;
  // A new logger that always writes these fields too (for example requestId), so you do not pass them again on every line.
  child(fields: Fields): Logger;
};

export type ErrorInfo = { name: string; message: string; stack?: string; cause?: ErrorInfo };

const PROJECT_URL = pathToFileURL(process.cwd()).href + "/";

// Turn an error into plain data that JSON.stringify can write. A real error has name/message/stack
// as non-enumerable properties, so JSON.stringify(new Error("x")) gives "{}".
// Follow the cause chain so the original error is not lost. Keep only the first 4 lines of the stack to keep the log short.
export function describeError(error: unknown): ErrorInfo {
  if (!(error instanceof Error)) return { name: "NonError", message: String(error) };
  return {
    name: error.name,
    message: error.message,
    stack: error.stack?.split("\n").slice(1, 5).map((line) => line.trim().replace(PROJECT_URL, "")).join(" | "),
    ...(error.cause === undefined ? {} : { cause: describeError(error.cause) }),
  };
}

export function createLogger(write: (line: string) => void = console.log, base: Fields = {}): Logger {
  const emit = (level: Level, msg: string, fields: Fields = {}) =>
    write(JSON.stringify({ time: new Date().toISOString(), level, msg, ...base, ...fields }));
  return {
    info: (msg, fields) => emit("info", msg, fields),
    warn: (msg, fields) => emit("warn", msg, fields),
    error: (msg, fields) => emit("error", msg, fields),
    child: (fields) => createLogger(write, { ...base, ...fields }),
  };
}

Three points are worth noting in this file. First, child returns a new logger that always writes the given fields. The server will create a child logger for every request with requestId, method and path already attached, so every log line of that request carries them automatically and nobody has to remember to pass them. Second, describeError follows cause, meaning the original error that another error wraps. Third, the logger takes a write function as a parameter, with console.log as the default. That way, when you write a test, you pass in a function that collects the lines into an array and you do not have to read the screen.

Connect the logger to the server: one ID per request, one line per reason

Now the server. There are four changes compared with the previous post, and I point at each one after you look at the code:

src/order-server.ts
import { randomUUID } from "node:crypto";
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";

import { createLogger, describeError, type Logger } from "./logger.ts";
import { listIssues, newOrderSchema } from "./order-schema.ts";
import { listOrders, type Order } from "./orders.ts";

const JSON_HEADERS = { "content-type": "application/json; charset=utf-8" };
const MAX_BODY_BYTES = 100_000;

// HTTP server for orders. Every request gets a short ID (requestId) that is attached to every log line of that request.
export function createOrderServer(orders: Order[], logger: Logger = createLogger()): Server {
  return createServer(async (request, response) => {
    const requestId = randomUUID().slice(0, 8);
    const log = logger.child({ requestId, method: request.method, path: request.url });
    const startedAt = performance.now();

    // One summary line for every request: the status code and the processing time. A 4xx is the fault
    // of the sender, so it is only a warn; a 5xx is the fault of the server, so it is an error.
    response.on("finish", () => {
      const status = response.statusCode;
      const level = status >= 500 ? "error" : status >= 400 ? "warn" : "info";
      log[level]("request", { status, ms: Math.round(performance.now() - startedAt) });
    });

    try {
      await route(request, response, orders, log);
    } catch (error) {
      // An unexpected error: write full detail to the log, but give the caller only a code to look up.
      log.error("unexpected error", { error: describeError(error) });
      if (response.headersSent) response.end();
      else sendError(response, 500, "Server error", { errorCode: requestId });
    }
  });
}

async function route(request: IncomingMessage, response: ServerResponse, orders: Order[], log: Logger): Promise<void> {
  if (request.url === "/orders" && request.method === "POST") return receiveOrder(request, response, orders, log);
  if (request.url === "/orders") return sendOrderList(response, orders);
  response.writeHead(404).end();
}

async function receiveOrder(request: IncomingMessage, response: ServerResponse, orders: Order[], log: Logger): Promise<void> {
  const body = await readBody(request);
  if (body === null) {
    log.warn("order rejected", { reason: "body too large", limitChars: MAX_BODY_BYTES });
    return sendError(response, 413, "The body you sent is too large");
  }

  let data: unknown;
  try {
    data = JSON.parse(body);
  } catch {
    log.warn("order rejected", { reason: "not JSON", length: body.length });
    return sendError(response, 400, "The body you sent is not valid JSON");
  }

  const result = newOrderSchema.safeParse(data);
  if (!result.success) {
    // Log the field names and the reasons, not the values the customer sent: phone number and name are personal data.
    const issues = listIssues(result.error);
    log.warn("order rejected", { reason: "invalid data", details: issues });
    return sendError(response, 400, "Invalid order", { details: issues });
  }

  const order: Order = {
    id: Math.max(0, ...orders.map((existing) => existing.id)) + 1,
    createdAt: new Date().toISOString(),
    source: "web",
    ...result.data,
  };
  orders.push(order);
  log.info("order received", { orderId: order.id, itemCount: order.items.length });
  response.writeHead(201, JSON_HEADERS).end(JSON.stringify({ id: order.id }));
}

// Read at most MAX_BODY_BYTES; past that, return null so the caller rejects it.
async function readBody(request: IncomingMessage): Promise<string | null> {
  let body = "";
  for await (const chunk of request) {
    body += chunk;
    if (body.length > MAX_BODY_BYTES) return null;
  }
  return body;
}

function sendError(response: ServerResponse, status: number, message: string, extra: object = {}): void {
  response.writeHead(status, JSON_HEADERS).end(JSON.stringify({ error: message, ...extra }));
}

function sendOrderList(response: ServerResponse, orders: Order[]): void {
  // No try/catch here any more: if listOrders throws, the outer function logs it and returns 500.
  // Build the content first and only then call writeHead(200): once a 200 is sent it cannot become a 500.
  const orderListJson = JSON.stringify(listOrders(orders), null, 2);
  response.writeHead(200, JSON_HEADERS).end(orderListJson);
}

The four changes are these. One: as soon as a request arrives, the server creates a requestId and a child logger, so every later line of this request carries that ID. Two: the finish event of the response writes exactly one summary line when the request ends, with the status code and the processing time in milliseconds, at level info, warn or error depending on the status code. Three: every time an order is rejected, the server logs the reason. For an order that fails the schema, I log the field name and the problem and deliberately do not log the values the customer sent, because name and phone number are personal data, and log files tend to live longer than you think. Four: the try/catch that wraps everything is the only place that catches unexpected errors. sendOrderList no longer needs to catch by itself.

On the customer side: when a 500 happens, the caller receives {"error":"Server error","errorCode":"..."}, which contains only a code. All internal detail, such as function names, file paths or the message of a library, stays in the log. The reason is that internal detail is what attackers love to read and what ordinary users cannot understand. The errorCode is identical to the requestId in the log, so if a customer complains, you only need to ask for that code.

One small detail I got wrong the first time: at first I wrote response.writeHead(200).end(JSON.stringify(listOrders(orders))) on one line. writeHead(200) runs first, then listOrders throws, and by that time the 200 has already been set. The summary log line of the request then said status: 200 right next to the error line, and the caller received an empty answer with a success code. The log I had just written was what exposed its own bug. That is why, in the code above, I build the content first and only then send the status code.

Try it: send three requests and read the log

The script below starts the server with two existing orders (a good one, and the broken order 1050 without a customer name), sends three requests, and prints the answers to stderr so they stay apart from the log, which goes to stdout:

try-log.ts
// Run the server with logging and one order of broken data, send three requests and print the log and the answers. Run: node try-log.ts
import type { AddressInfo } from "node:net";

import { createOrderServer } from "./src/order-server.ts";
import type { Order } from "./src/orders.ts";

const goodOrder: Order = {
  id: 1041,
  createdAt: "2026-11-03T08:12:00+07:00",
  source: "web",
  customer: { name: "Nguyen An", phone: "0901000001" },
  items: [{ name: "Milk coffee", price: 29000, quantity: 2 }],
};
// Order 1050 has a phone number but no customer name: broken data already sitting in the list.
const brokenOrder = { id: 1050, createdAt: "2026-11-04T09:00:00+07:00", source: "legacy-pos", customer: { phone: "0901000050" }, items: [{ name: "Peach tea", price: 35000, quantity: 1 }] } as unknown as Order;

const server = createOrderServer([goodOrder, brokenOrder]);
await new Promise<void>((resolve) => server.listen(0, resolve));
const base = `http://localhost:${(server.address() as AddressInfo).port}/orders`;
const customer = { name: "Pham Dung", phone: "0901000010" };

const send = async (label: string, init?: RequestInit) => {
  const reply = await fetch(base, init);
  console.error(`→ ${label}: ${reply.status} ${(await reply.text()).replace(/\s+/g, " ").slice(0, 110)}`);
};

await send("POST valid order", { method: "POST", body: JSON.stringify({ customer, items: [{ name: "Milk coffee", price: 29000, quantity: 2 }] }) });
await send("POST quantity is a word", { method: "POST", body: JSON.stringify({ customer, items: [{ name: "Milk coffee", price: 29000, quantity: "two" }] }) });
await send("GET list");
server.close();

You run node try-log.ts (the requestId values and the times on your machine will be different). The part that the customer receives is this:

node try-log.ts (the stderr part: the answers)
→ POST valid order: 201 {"id":1051}
→ POST quantity is a word: 400 {"error":"Invalid order","details":[{"field":"items.0.quantity","problem":"Quantity must be a number"}]}
→ GET list: 500 {"error":"Server error","errorCode":"3ecf9d19"}

And this is the log of the server (stdout), six lines for three requests, from the very same run:

node try-log.ts (the stdout part: the log)
{"time":"2026-11-17T11:54:24.089Z","level":"info","msg":"order received","requestId":"41299b98","method":"POST","path":"/orders","orderId":1051,"itemCount":1}
{"time":"2026-11-17T11:54:24.090Z","level":"info","msg":"request","requestId":"41299b98","method":"POST","path":"/orders","status":201,"ms":7}
{"time":"2026-11-17T11:54:24.097Z","level":"warn","msg":"order rejected","requestId":"100a0afd","method":"POST","path":"/orders","reason":"invalid data","details":[{"field":"items.0.quantity","problem":"Quantity must be a number"}]}
{"time":"2026-11-17T11:54:24.098Z","level":"warn","msg":"request","requestId":"100a0afd","method":"POST","path":"/orders","status":400,"ms":1}
{"time":"2026-11-17T11:54:24.100Z","level":"error","msg":"unexpected error","requestId":"3ecf9d19","method":"GET","path":"/orders","error":{"name":"Error","message":"Could not list order 1050","stack":"at src/orders.ts:27:13 | at Array.map (<anonymous>) | at listOrders (src/orders.ts:22:17) | at sendOrderList (src/order-server.ts:94:40)","cause":{"name":"TypeError","message":"Cannot read properties of undefined (reading 'toUpperCase')","stack":"at customerLabel (src/orders.ts:13:30) | at src/orders.ts:24:40 | at Array.map (<anonymous>) | at listOrders (src/orders.ts:22:17)"}}}
{"time":"2026-11-17T11:54:24.100Z","level":"error","msg":"request","requestId":"3ecf9d19","method":"GET","path":"/orders","status":500,"ms":1}

Let me point at three places. First, the requestId of the error line is 3ecf9d19, identical to the errorCode the customer received on the last line of the stderr part. If a customer calls, you find exactly that code. Second, the error line has a message of "Could not list order 1050", which says which order is broken, and cause keeps the original error TypeError: Cannot read properties of undefined (reading 'toUpperCase') together with where it happened, customerLabel (src/orders.ts:13:30). That pair answers two questions that the old stack trace could not: which order, and which line the root error is on. Third, the order rejected for a wrong quantity is only a warn, not an error, and the log says exactly which field (items.0.quantity) without exposing a name or a phone number.

Finally, to find every line of one request, you filter by its ID. For example with grep:

Filter the log by request ID
node try-log.ts 2>/dev/null | grep 3ecf9d19

This command runs the server again so the ID will be different, but when the server runs for real and the log is written to a file, you use exactly this method with the code the customer gives you. Every line is JSON, so you can also filter by level, for example keeping only the lines with "level":"error".

What to log, and what not to

If you follow along, the hardest part is not the code but the decisions about content. I follow the principles below, and I think you should keep them in a real project.

Log what helps the next person answer "what, when, whose, and why": the request ID, the business ID (such as orderId), the name of the wrong field, the processing time. Do not log personal data and secrets: phone numbers, passwords, tokens, API keys. I wrote a test for this, which you will see below. The reason is that log files are copied to many places (monitoring tools, error emails, screenshots sent to colleagues), so whatever you write in them should be treated as already out of the project.

Do not swallow errors. An empty catch {} block or a catch (e) { console.log("error") } is worse than not catching, because it turns the error into silence. You will see a system that "runs" while the data is wrong, with no trace to follow. If you do not know how to handle it, let the error go up to a higher level, where a central catch block exists, like the catch in createOrderServer.

And do not log everything at level error. If a bad order logs error, then when the website sends five hundred bad orders you have five hundred red lines hiding one real error. I repeat this because it is very easy to do the wrong way round.

Write a test for the log

Logs are also behaviour of the program. Without a test, one day someone edits the code, the requestId disappears, and nobody notices. Because the logger takes a write function, the test only needs to collect the lines into an array and check them. This is the most important test: it sends an order with the phone number 0901234567, then asserts that this number does not appear in any log line.

src/order-server.log.test.ts
import type { AddressInfo } from "node:net";
import { expect, test } from "vitest";

import { createLogger } from "./logger.ts";
import { createOrderServer } from "./order-server.ts";
import type { Order } from "./orders.ts";

// Run the server with a logger that writes into an array, send one request, return the answer and the parsed log lines.
async function call(orders: Order[], path: string, init?: RequestInit) {
  const lines: Record<string, unknown>[] = [];
  const server = createOrderServer(orders, createLogger((line) => lines.push(JSON.parse(line))));
  await new Promise<void>((resolve) => server.listen(0, resolve));
  try {
    const response = await fetch(`http://localhost:${(server.address() as AddressInfo).port}${path}`, init);
    const body = await response.text();
    await new Promise((resolve) => setTimeout(resolve, 20)); // wait for the "request" line to be written
    return { status: response.status, body, lines };
  } finally {
    server.close();
  }
}

test("a rejected order: the warn log has the field name, not the phone number of the customer", async () => {
  const body = JSON.stringify({ customer: { name: "An", phone: "0901234567" }, items: [{ name: "Coffee", price: 29000, quantity: "two" }] });
  const { lines } = await call([], "/orders", { method: "POST", body });
  const rejected = lines.find((line) => line.msg === "order rejected");
  expect(rejected).toMatchObject({ level: "warn", details: [{ field: "items.0.quantity" }] });
  expect(JSON.stringify(lines)).not.toContain("0901234567");
});

To run it, add "vitest": "5.1.0" to devDependencies in package.json, run npm install, and then npx vitest run src/order-server.log.test.ts:

Output
 Test Files  1 passed (1)
      Tests  1 passed (1)

In the demo repo I wrote two more tests of the same kind: a 500 error must have a requestId equal to the errorCode returned to the customer and must carry the original error in cause, and every request must have exactly one summary line. Together with the tests of the earlier posts there are 47 green tests in that repo. If someone ever "conveniently" writes the whole body of a request into the log to make debugging easier, this test turns red immediately.

The errors now leave traces, but what about slow requests?

By now the order server of the Mộc café has something it did not have before: when something goes wrong, it tells the story in its log. Every request has an ID, every error has an address, and the data of customers is not exposed. But notice one thing in the log lines above: every request records ms, the processing time, and for now all those numbers are a few milliseconds. When some request starts to be slow, the log will tell you which request is slow and how slow. It will not yet tell you which line of code is slow. How to find the slow spot without guessing is the job of the next posts.

You can follow the whole story in the series Taking over an old project. If you want to review how to read an error, the post how to read a stack trace is the place to start, and the questions about error handling and APIs are in the interview question bank.

Get the next post by email.

One email a week, only when there is something worth reading. No spam.