Skip to main content
Proper error handling is essential for building reliable bots. grammY provides multiple mechanisms to catch and handle errors at different levels.

Error Types

grammY has three main error types:

BotError

Thrown when middleware throws an error. Wraps the original error and provides the context:
unknown
The original error that was thrown
Context
The context object being processed when the error occurred

GrammyError

Thrown when a Bot API call fails (Telegram returned an error):
number
Telegram’s error code (e.g., 400, 401, 403, 429)
string
Human-readable error description from Telegram
ResponseParameters
Additional error parameters (e.g., retry_after for rate limits)
string
The Bot API method that was called
object
The parameters that were sent

HttpError

Thrown when the HTTP request to Telegram fails (network error):
unknown
The underlying error (e.g., network timeout, connection refused)

Global Error Handler

Set a global error handler with bot.catch():
Always set an error handler before starting your bot!Without an error handler, unhandled errors will crash your bot and stop long polling.The default error handler will:
  1. Log the error to console
  2. Stop the bot if polling
  3. Re-throw the error

Error Boundaries

Error boundaries let you handle errors in specific middleware subtrees:

Nested Error Boundaries

Error boundaries can be nested:

Suppressing Errors

Suppress errors by not re-throwing:

Common Error Scenarios

Rate Limiting (Error 429)

grammY automatically handles rate limiting for getUpdates during long polling. This manual handling is only needed for other API calls.

Unauthorized (Error 401)

Conflict (Error 409)

Bad Request (Error 400)

Forbidden (Error 403)

Try-Catch in Middleware

Handle errors locally in middleware:
Use try-catch for expected errors that you want to handle locally. Let unexpected errors bubble up to error handlers.

Graceful Degradation

Handle errors without stopping the bot:

Retry Logic

Implement retry logic for transient failures:

Error Monitoring

Integrate with error monitoring services:

Timeout Handling

Handle long-running operations with timeouts:

Logging Best Practices

Structured error logging:

User-Friendly Error Messages

Provide helpful feedback to users:

Development vs Production

Different error handling for environments:

Best Practices

Set Error Handler First
Don’t Swallow ErrorsAlways log errors, even if you handle them:
Avoid Errors in Error HandlersError handlers should be rock-solid:
Test Error PathsTest that your error handling works: