Thuta Learning
Node.js
AdvancedWeb DevelopmentBeginner

Errors, Logging & Observability

Node.jsLesson 2035 min

What you'll walk away with

  • Separate client-safe errors from internal ones and return the right status
  • Add a request ID to every log line automatically with AsyncLocalStorage
  • Redact secret fields before anything is logged
  • Explain why a process should shut down, not carry on, after unhandledRejection or uncaughtException

Explain it simply

Errors and observability in plain language

When something breaks in production, two audiences see the error. The user needs a short, clear message about what happened and what to do, and should never see internal details. The on-call engineer needs the opposite: which request, which dependency, which error code, in detail.

Observability is the ability to understand what is happening inside a system from the outside. Its three main parts are searchable structured logs, metrics that show rates and totals, and traces that follow one request across services.

Problem → Why → Solution

The problem: 'something broke' and a password in the log

A customer reports that checkout failed. The log has thousands of console.log('error', err) lines, but nobody can tell which one belongs to this customer, because there is no request ID. Worse, a login error logged the whole req.body, so passwords sit in the log system in plain text, and the customer's browser shows a stack trace that names the database host.

login-route.mjs
app.post('/login', async (req, res) => {
  try {
    await auth.login(req.body.email, req.body.password);
    res.sendStatus(204);
  } catch (err) {
    console.log('login error', err, req.body); // free text + the password
    res.status(500).send(err.stack); // internals sent to the browser
  }
});

Why these logs are useless and dangerous

Free-text logs cannot be filtered or counted, and without a request ID you cannot connect related lines. Dumping whole objects leaks secrets, and sending a stack trace to the client hands an attacker a map of your system. Each error needs to be classified at the boundary, with separate output for each audience.

Core concept: classify, add context, output for two audiences

Split errors into two groups. Operational errors are expected: an order that does not exist, a failed validation, a database that is briefly unreachable. Programmer errors are bugs, such as reading a property of undefined. Where an error is created, use an AppError class carrying a status, a machine-readable code such as ORDER_NOT_FOUND, and an expose flag. Only exposed messages go to the client; everything else becomes a generic 500. When wrapping an error, keep the original with new AppError(message, { cause }).

Write logs as one JSON line each: level, event name, requestId and fields. A log platform can then search and count them with queries such as level=error AND code=DB_UNAVAILABLE. Instead of passing the request ID through every function, use AsyncLocalStorage from node:async_hooks: inside requestContext.run({ requestId }, fn), getStore() returns that request's context however many awaits deep you are.

Decide what goes into a log with an allowlist too. Include fields that help searching, such as the event name, IDs, status, duration and error code, and redact passwords, tokens, cookies and card numbers before they ever reach the log. Each line should answer 'what happened, in whose request, and why'.

Kind of errorClient responseLog level
failed validation400 + what was wrongwarn or info
record not found404 + codewarn
dependency down503 or 500 + generic messageerror
bug (TypeError etc.)500 + generic messageerror + stack

Process-level errors are different. In Node.js a promise rejection that nobody catches crashes the process with exit code 1 by default. Adding an unhandledRejection or uncaughtException listener stops that crash, but the process state can no longer be trusted. So in the listener, write a fatal log, start a graceful shutdown and let the process exit; the process manager starts a fresh one.

One error, two outputs
  1. Failure: an AppError or a bug
  2. Classify it at the boundary
  3. Client: code + safe message
  4. Log: requestId + redacted detail
  5. Fatal? Shut the process down

The client response and the log line come from the same error but use different allowlists of fields.

General pattern

javascript
class AppError extends Error {
  constructor(message, { status, code, expose, cause } = {}) {
    super(message, { cause }); // then store status, code and expose
  }
}

try {
  return await work();
} catch (error) {
  logger.error({ requestId, code: error.code, message: error.message });
  return error.expose ? publicResponse(error) : genericServerError();
}

The place that creates the error knows its status and code; the boundary (a route handler or error middleware) does the logging and the response in one place.

Worked example: three outcomes of an order lookup

This example simulates three requests: a successful lookup, a 404 that may be shown to the client, and an internal error caused by an unreachable database. Each request runs inside an AsyncLocalStorage context, so the log function gets the requestId without a parameter. The JSON lines are for operators and the -> lines are what the client receives. In the third request, notice that the log contains the cause while the client only gets a generic message.

order-errors.mjs
import { AsyncLocalStorage } from 'node:async_hooks';

class AppError extends Error {
  constructor(message, { status = 500, code = 'INTERNAL', expose = false, cause } = {}) {
    super(message, { cause });
    this.name = 'AppError';
    this.status = status;
    this.code = code;
    this.expose = expose; // may the client see this message?
  }
}

const requestContext = new AsyncLocalStorage();

function log(level, event, fields = {}) {
  const requestId = requestContext.getStore()?.requestId ?? null;
  // A real logger also adds a timestamp; it is left out so the output is repeatable.
  console.log(JSON.stringify({ level, event, requestId, ...fields }));
}

function toResponse(error) {
  if (error instanceof AppError && error.expose) {
    return { status: error.status, body: { error: error.code, message: error.message } };
  }
  return { status: 500, body: { error: 'INTERNAL', message: 'Something went wrong' } };
}

async function findOrder(id) {
  if (id === 'missing') {
    throw new AppError(`Order ${id} not found`, {
      status: 404, code: 'ORDER_NOT_FOUND', expose: true,
    });
  }
  if (id === 'db-down') {
    const cause = new Error('connect ECONNREFUSED 10.0.0.5:5432');
    throw new AppError('Order lookup failed', { code: 'DB_UNAVAILABLE', cause });
  }
  return { id, total: 42 };
}

async function handle(requestId, orderId) {
  return requestContext.run({ requestId }, async () => {
    try {
      const order = await findOrder(orderId);
      log('info', 'order_found', { orderId });
      return { status: 200, body: order };
    } catch (error) {
      const response = toResponse(error);
      log(response.status >= 500 ? 'error' : 'warn', 'request_failed', {
        status: response.status,
        code: error.code,
        message: error.message,
        cause: error.cause?.message, // undefined fields vanish from JSON
      });
      return response;
    }
  });
}

const requests = [['req-1', 'A7'], ['req-2', 'missing'], ['req-3', 'db-down']];
for (const [requestId, orderId] of requests) {
  const { status, body } = await handle(requestId, orderId);
  console.log(`-> ${status} ${JSON.stringify(body)}`);
}

Code breakdown

  1. Error with metadatasuper(message, { cause });

    The cause option of the Error constructor keeps the original error as error.cause, so the real reason (ECONNREFUSED) survives the wrapping.

  2. Context without parametersconst requestId = requestContext.getStore()?.requestId ?? null;

    getStore() returns the object passed to the run() call that started the current async chain; findOrder never needs a requestId parameter.

  3. Two audiencesif (error instanceof AppError && error.expose) {

    Only exposed AppErrors send their code and message to the client. Bugs such as a TypeError and unexposed errors become 'Something went wrong'.

  4. Level by severitylog(response.status >= 500 ? 'error' : 'warn', 'request_failed', {

    A 404 is the client's problem, so it is a warn; a 500 is ours, so it is an error. Alerts are usually based on the error level only.

  5. Request scopereturn requestContext.run({ requestId }, async () => {

    In Express this run() call lives in a middleware, taking the ID from a header such as x-request-id or generating one with crypto.randomUUID().

You should see
{"level":"info","event":"order_found","requestId":"req-1","orderId":"A7"}
-> 200 {"id":"A7","total":42}
{"level":"warn","event":"request_failed","requestId":"req-2","status":404,"code":"ORDER_NOT_FOUND","message":"Order missing not found"}
-> 404 {"error":"ORDER_NOT_FOUND","message":"Order missing not found"}
{"level":"error","event":"request_failed","requestId":"req-3","status":500,"code":"DB_UNAVAILABLE","message":"Order lookup failed","cause":"connect ECONNREFUSED 10.0.0.5:5432"}
-> 500 {"error":"INTERNAL","message":"Something went wrong"}

Process-level fatal errors

Register fatal handlers once, at the top of the entry point. What matters is that the handler does not keep the process running: it sets the exit code to 1, starts shutdown, and as a last resort calls process.exit(1) from an unref'd timer. Setting exitCode alone does not end a process while a server is still open.

fatal-handlers.mjs
// Register once, at the very top of the entry point.
function onFatal(kind) {
  return (error) => {
    console.error(JSON.stringify({
      level: 'fatal', event: kind, name: error?.name, message: error?.message,
    }));
    process.exitCode = 1;
    // Stop taking new work and shut down (lesson 21); never keep serving
    // traffic as if nothing happened. The unref'd timer is a last resort.
    setTimeout(() => process.exit(1), 5_000).unref();
  };
}

process.on('uncaughtException', onFatal('uncaught_exception'));
process.on('unhandledRejection', onFatal('unhandled_rejection'));
console.log('fatal handlers installed:', process.listenerCount('unhandledRejection'));

In real projects

An observability stack in production

Real projects do not call console.log directly; they use a JSON logger such as pino, which supports redact paths, log levels and request IDs out of the box. The app writes to stdout, and the container platform collects the lines and ships them to a searchable system.

  • Return the request ID in a response header, so support can ask a customer for that ID and find every related log line at once.
  • Alert on metrics counted per error code, such as DB_UNAVAILABLE per minute, not on individual log lines.
  • In systems with many services, a standard such as OpenTelemetry carries a trace ID between services so one request's whole journey is visible.

Common mistakes

Common error-handling and logging mistakes

Sending err.message or the stack to the client

A database driver's message can contain host names, table names and even parts of the query. Send only the messages of AppErrors created to be exposed, and replace everything else with a generic message.

Logging whole request bodies or headers

req.body contains passwords; req.headers contains authorization tokens and cookies. Anyone with access to the log system can read them, and retention may keep them for years. Pick the fields you log and redact secret keys.

Carrying on after unhandledRejection

A handler that only logs leaves the process taking traffic with half-finished transactions and leaked connections. Log, shut down, and let the process manager start a clean process.

Best practices

Best practices

  • Keep error codes as stable strings such as ORDER_NOT_FOUND; message wording may change, but clients and dashboards rely on the code.
  • Log an error once, at the boundary; logging and rethrowing at every layer produces duplicate lines.
  • Write logs to stdout as JSON and leave rotation and shipping to the platform.
  • Test redaction: log an object containing a password and assert that the output does not contain it.

Mini challenge

Mini challenge: a redacting JSON logger

Write an AppError class with status, code and details, and a logger that writes an error as one JSON line. The logger must find fields whose key looks like password, token or authorization, even inside nested objects, and replace them with [REDACTED]. Make the clock injectable so the output can be tested.

  • AppError has status (default 500), code (default INTERNAL) and details
  • redact(value) walks nested objects and arrays recursively
  • The log line includes time, level, requestId, name, code, status and message
  • createLogger({ now }) accepts a fixed clock
redacting-logger.mjs
const SECRET_KEY = /pass(word)?|token|secret|authorization|cookie|api[-_]?key/i;

class AppError extends Error {
  // TODO: constructor(message, { status, code, details } = {})
}

function redact(value) {
  // TODO: arrays -> map; plain objects -> copy with secret keys replaced
  // TODO: primitives and null -> return unchanged
}

function createLogger(options = {}) {
  // TODO: now() defaults to new Date().toISOString(); write defaults to console.log
  // TODO: return { error(error, { requestId }) { ...one redacted JSON line... } }
}

// TODO: log an AppError whose details include a password and an authorization header
// TODO: log a plain TypeError and check that code and status simply disappear

Expected: In the first line, password and authorization are [REDACTED] while email and user-agent are unchanged. The second line is the TypeError, with no code or status fields.

Show hint

Object.fromEntries(Object.entries(obj).map(...)) builds a new copy without mutating the original. JSON.stringify drops fields whose value is undefined, so the TypeError's log line simply has no code or status.

Show solution
redacting-logger.mjs
const SECRET_KEY = /pass(word)?|token|secret|authorization|cookie|api[-_]?key/i;

class AppError extends Error {
  constructor(message, { status, code, details } = {}) {
    super(message);
    this.name = 'AppError';
    this.status = status ?? 500;
    this.code = code ?? 'INTERNAL';
    this.details = details;
  }
}

function redact(value) {
  if (Array.isArray(value)) return value.map(redact);
  if (value === null || typeof value !== 'object') return value;
  return Object.fromEntries(
    Object.entries(value).map(([key, inner]) =>
      [key, SECRET_KEY.test(key) ? '[REDACTED]' : redact(inner)]),
  );
}

function createLogger(options = {}) {
  const now = options.now ?? (() => new Date().toISOString());
  const write = options.write ?? console.log;
  return {
    error(error, { requestId }) {
      const entry = {
        time: now(),
        level: 'error',
        requestId,
        name: error.name,
        code: error.code,
        status: error.status,
        message: error.message,
        details: error.details,
      };
      write(JSON.stringify(redact(entry)));
    },
  };
}

// A fixed clock keeps this demo's output identical on every run.
const logger = createLogger({ now: () => '2026-01-01T00:00:00.000Z' });

logger.error(new AppError('Login failed', {
  status: 401,
  code: 'BAD_CREDENTIALS',
  details: {
    email: 'mya@example.com',
    password: 'hunter2',
    headers: { authorization: 'Bearer abc.def', 'user-agent': 'curl/8' },
  },
}), { requestId: 'req-77' });

logger.error(new TypeError("Cannot read properties of undefined (reading 'id')"), {
  requestId: 'req-78',
});

Quick quiz 1 / 3

A database outage raises an AppError with expose: false. What should the client receive?

Quick quiz 2 / 3

Inside requestContext.run({ requestId: 'r1' }, async () => { await a(); await b(); }), what does getStore() return when called from b()?

Quick quiz 3 / 3

A server has only process.on('unhandledRejection', (e) => console.error(e)). What happens when a rejection goes unhandled?

What to remember

  • Classify errors with an AppError carrying status, code and expose, and send only exposed messages to clients.
  • Write logs as JSON lines with level, event and requestId, and carry request context with AsyncLocalStorage.
  • Redact fields such as password, token and authorization before logging.
  • Keep the original error with { cause } when wrapping.
  • After unhandledRejection or uncaughtException, log and shut down rather than carrying on.

Errors — Node.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Errors, Logging & Observability | Thuta Learning