# Add Error Handling to a grammY Bot

Yes. An agent adds a bot.catch handler that tells GrammyError from HttpError, puts error boundaries around your composers, proves it with a check, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-error-handling/grammy/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how each bot starts and what happens when a handler throws. In a repository laid out like grammyjs/examples, `echo.ts` and `runner.ts` create a `Bot`, register `bot.on('message:text', ...)` and start with `bot.start()` or the runner's `run(bot)`, with no error handler at all. `stats.ts` has one line, `bot.catch(err => console.error(err))`, which prints the whole `BotError` object. `scaling/index.ts` attaches `apiThrottler()` as an API transformer, a session, two routers and a composer whose final `composer.use` answers every unmatched update, again with no `bot.catch`. `fastify.ts` is the webhook case: `webhookCallback(bot, 'fastify', { secretToken })` behind `server.setErrorHandler`. `package.json` pins `grammy` at `^1.4.3` and runs examples with `ts-node` under a strict `tsconfig.json`.

Without a handler, grammY's default is to log the update, say that no error handler was set, and rethrow, which stops long polling. The agent writes `shared/errors.ts` with one `handleError(err: BotError)` and installs it with `bot.catch` in `echo.ts`, `runner.ts`, `stats.ts` and `scaling/index.ts`. The handler reads `err.ctx.update.update_id` and the chat id for the log line, then branches on `err.error`: a `GrammyError` is Telegram refusing the call, with `description` and `error_code`, so a 403 from a user who blocked the bot is logged at info and a 400 is logged with the method and payload; an `HttpError` is the network, logged with its cause; anything else is a bug in the handler code and is logged with the stack. Nothing is rethrown, so one bad update does not end polling.

For the webhook example the shape is different and the agent treats it so: `webhookCallback` answers Telegram, and an error inside it reaches Fastify's error handler, so `fastify.ts` keeps `setErrorHandler` and gains the same `bot.catch`, which runs first and keeps the response a 200 so Telegram does not redeliver the update. In `scaling/index.ts` the add and multiply routers are wrapped with `bot.errorBoundary(handleError, router)`, so a throw inside one router is handled there and the composer's fallback still runs for the update.

The repository has no test framework, so the agent proves the handler the way the repository runs code: a `check-errors.ts` script run with `ts-node`, which installs an API transformer that throws a constructed `GrammyError` with `error_code: 403` for `sendMessage`, feeds an update through `bot.handleUpdate`, and asserts with `node:assert` that `handleError` saw a `GrammyError` and that `handleUpdate` resolved rather than rejected. The same script repeats it with an `HttpError` and with a plain `Error` thrown from a handler. The agent runs the script and quotes its output.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add error handling to the grammY bots in this repository. Read package.json, tsconfig.json, echo.ts, runner.ts, stats.ts, fastify.ts, scaling/index.ts, scaling/composers/index.ts and scaling/routers/add.ts first. Write shared/errors.ts exporting a handleError for bot.catch that logs the update id and chat, distinguishes GrammyError with its error_code and description from HttpError and from any other Error, and never rethrows. Install it with bot.catch in echo.ts, runner.ts, stats.ts, scaling/index.ts and fastify.ts, and wrap the two routers in scaling with bot.errorBoundary. Write check-errors.ts that uses an API transformer throwing a constructed GrammyError, then an HttpError, then a plain Error from a handler, drives updates through bot.handleUpdate and asserts with node:assert that the handler saw each kind and that handleUpdate resolved. Run it with ts-node, add a README section, and open a pull request quoting the output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that adds `shared/errors.ts` and `check-errors.ts`, adds one `bot.catch` line to five examples, wraps the routers in `scaling/index.ts`, and extends the README with a short section on what the handler does with each error kind. The description quotes the check script's three passing cases and shows the log line each kind produces.

The run's record keeps the `ts-node` run of the check, so a reviewer can read the asserted behaviour for the 403, the network error and the handler bug rather than infer it from the handler's branches.

Before merging, a reviewer decides whether a 403 from a blocked user should also remove that chat from any session store the real bot has, and whether 429 responses should go to the `auto-retry` plugin rather than the log. Both are named in the pull request as follow-ups, not guessed.

## Run it on every bot without a bot.catch

A team that runs several bots starts one run per repository with one `POST /o/{org}/sessions` each, this prompt as `input` and the repository in `resources`. Each run reads how that bot starts, polling, runner or webhook, and installs the handler the way that bot needs it, so a webhook bot keeps answering Telegram with a 200 and a polling bot keeps polling.

Send a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run it already started. The key's `webhook_url` reports when each run the key starts finishes, with `session_url` to read the pull request from and the run's final answer in `result`.

## Why run it on Rush?

The handler is ten lines and the proof is the hard part: constructing a `GrammyError` the way the library does, driving an update through the bot without a token or a network, and showing that polling would have survived. The agent does that in its own sandbox with the repository's own `ts-node`, and keeps the output, so the pull request carries evidence rather than a description of `bot.catch`.

Because the change touches five entry points in the same way, review is one handler, one script and five one-line diffs. Across several bots the job runs in parallel, one sandbox and one pull request each, each fitted to how that bot is started.

## Frequently asked questions

### What does grammY do with an error when there is no bot.catch?

Its default handler logs the update and the error, prints that no error handler was set, and rethrows. Under long polling that rejection ends `bot.start()`, so one blocked user can stop the bot for everyone. Installing `bot.catch` is what keeps polling alive.

### Why not rethrow after logging?

Because the only thing a rethrow does under polling is stop the loop, and under a webhook it turns a handled update into a non-200 response that Telegram redelivers. The handler logs, decides, and returns; a case that should stop the process is a deliberate `process.exit` the team adds.

### Does this cover rate limits?

A 429 arrives as a `GrammyError` with `error_code: 429` and a `retry_after` in its parameters, and the handler logs it as such. Retrying is a transformer's job: the `scaling` example already uses the throttler, and the `auto-retry` plugin handles 429 by waiting and resending. The pull request names it rather than adding a dependency unasked.

### Why error boundaries on the routers only?

Because the routers hold the state machine for `/add` and `/multiply`, and a throw there should not stop the composer's fallback reply. `bot.catch` already covers everything else; a boundary on every piece of middleware would hide where errors come from.

## More grammY jobs

- [Add Graceful Shutdown to a grammY Bot](https://getrush.ai/run/add-graceful-shutdown/grammy/)
- [Add Persistent Sessions to a grammY Telegram Bot With Redis](https://getrush.ai/run/add-persistent-sessions/grammy/)
- [Add Rate Limiting to a grammY Telegram Bot](https://getrush.ai/run/add-rate-limiting/grammy/)

## More jobs like this: Hand off a long task

- [Add Error Prone to a Gradle Build](https://getrush.ai/run/add-errorprone/gradle/)
- [Add Error Prone to a Maven Build](https://getrush.ai/run/add-errorprone/maven/)
- [Bundle a VS Code Extension with esbuild](https://getrush.ai/run/add-esbuild-bundling/vscode-extension/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
