Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท Commands and Events

Middleware and Error Handling

Learn the middleware pattern for chat bots - an onion-style compose function, logging, timing, per-user throttling, deduplication, error boundaries, and safe handling of unhandled rejections - with runnable examples.

Some code has to run for every update: log it, time it, ignore duplicates, block spammers, load the user's settings, catch errors. Copying that into every handler is tedious and easy to forget. The standard solution is middleware: small functions that wrap the handling of an update, each deciding whether to pass control to the next one. grammY, Telegraf, discord.js collectors, Express and Koa all use the same pattern. You will build the core of it in a dozen lines.

The onion model

A middleware is async (ctx, next) => { ... }. Calling await next() runs the rest of the chain. Code before next() runs on the way in, code after it on the way out, like layers of an onion. A middleware that does not call next() stops the chain (for example because it detected spam).

The onion model

Logger Outer layer
Error boundary Catches failures
Throttle May stop the chain
Handler The core

Before next() goes in, after next() comes out

1 / 2

The compose function is short. It builds the chain by recursion: dispatch(i) runs middleware i with a next that runs i + 1.

Node.js compose(): the heart of middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first run goes in through every layer, reaches the handler and comes back out. In the second the blocker stops the chain, so the inner layer and the handler never run, but the outer layer still gets its "out" step, which is why an outer error boundary or logger can always finish its job.

Useful middleware you will write

Logging and timing

Log one structured line per update: the kind, who sent it, how long it took and whether it failed. Structured (JSON) logs are easy to search later.

Deduplication

Platforms sometimes deliver an event twice (a webhook retried after a slow response, a gateway resume). Keep a short-lived set of recent update ids and skip repeats.

Per-user throttling

Limit how fast one user can trigger the bot. A token bucket allows short bursts but a low average rate:

Node.js Logger, dedupe and throttle in one chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first three requests in the burst pass, then the bucket is empty, so the next two are limited. The repeated id is skipped by the dedupe layer. After two quiet seconds the bucket has refilled enough for another request. Because Ben has his own bucket, Ana's flood never affects him.

Error boundaries

Every handler can throw: a bug, a failed API call, bad data. The rule is that one failing update must never stop the bot and the user must never be left in silence. An error-boundary middleware at the outer edge catches everything, logs the technical detail, and sends a short friendly message.

Distinguish three kinds of failure:

  • Expected user errors (bad input): handle in the handler with a clear message. Not exceptions at all, or a special UserError class.
  • Platform errors (rate limit, blocked bot, deleted message): often safe to ignore or retry. A user who blocked your bot should be removed from broadcasts, not logged as a crash.
  • Bugs (TypeError, undefined): log with a stack trace and the update id, and tell the user "Something went wrong."
Node.js An error boundary that classifies failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The classification keeps the logs meaningful. If every blocked user appeared as an error, real bugs would drown in noise.

Process-level safety nets

Even with boundaries, an exception can occur outside any handler (a timer callback, an event emitter without an error listener). Node terminates on an unhandled rejection by default, which is the correct behaviour in a supervised environment: log the problem, exit with a non-zero code and let your process manager restart the bot. Do not swallow everything and keep running in an unknown state. This listing is read-only:

JavaScript
process.on('unhandledRejection', (reason) => {
  console.error('unhandled rejection', reason);
  process.exitCode = 1;
  // flush logs, close the database, then exit
});

process.on('SIGTERM', async () => {
  console.log('shutting down: finishing current updates');
  await bot.stop(); // stop polling, wait for handlers
  process.exit(0);
});

Graceful shutdown on SIGTERM matters when you deploy: the host sends the signal, waits a few seconds, then kills the process. A bot that finishes its current update and confirms its offset before exiting avoids replaying or losing messages.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if a middleware does not call next()?

    Calling next() is what continues the chain. Skipping it is how throttles and permission checks block an update.
  2. 2. Where should the error boundary sit in the chain?

    An outer boundary wraps all inner layers, so any exception thrown inside is caught and handled in one place.
  3. 3. A user blocked your bot and sendMessage fails with 403. What is the best reaction?

    A 403 for a blocked bot is a normal event, not a bug. Record it and stop messaging that user.
  4. 4. Why is deduplication useful?

    Retried webhooks and resumed sessions may repeat an event. Remembering recent ids prevents double replies.

Summary

  • Middleware wraps update handling: code before next() runs inward, after it outward; not calling next() stops the chain.
  • compose builds the chain; logging, dedupe, throttling, user loading and permission checks are typical layers.
  • A token bucket per user allows short bursts but a low average rate.
  • Put an error boundary at the outside; classify user errors, platform errors and bugs; log bugs with the update id.
  • Let the process exit on unhandled rejections under a supervisor and shut down gracefully on SIGTERM.

Next: Formatting Text and Escaping