Skip to main content
grammY provides three main error types to help you handle different failure scenarios in your bot.

BotError<C>

Thrown when middleware throws an error. Wraps the original error and provides access to the context.

Properties

  • error: The original error that was thrown by your middleware
  • ctx: The context object being processed when the error occurred
  • message: A descriptive error message
  • name: Always "BotError"
  • stack: Stack trace from the original error (if available)

When it occurs

BotError is thrown whenever an error occurs during middleware execution:

Handling BotError

Use bot.catch() to install an error handler:

Accessing context from errors

The ctx property lets you access update information when an error occurs:

Example: Retry on error

GrammyError

Thrown when the Telegram Bot API returns an error response.

Properties

  • error_code: Telegram’s error code (e.g., 400, 404, 429)
  • description: Human-readable error description from Telegram
  • parameters: Additional parameters (e.g., retry_after for rate limits)
  • method: The API method that was called (e.g., "sendMessage")
  • payload: The parameters passed to the API method
  • ok: Always false

Common Error Codes

When it occurs

GrammyError is thrown when Telegram’s API returns an error:

Example: Handling specific errors

Example: Handling message deletion

Example: Handling bot blocking

ResponseParameters

Some errors include additional parameters:
Example:

HttpError

Thrown when the HTTP request to Telegram’s servers fails.

Properties

  • error: The underlying network error
  • message: Descriptive error message
  • name: Always "HttpError"

When it occurs

HttpError is thrown when:
  • Network connection fails
  • DNS resolution fails
  • Request times out
  • Connection is aborted
  • API transformer function throws

Example: Retry on network failure

Error Handling Patterns

Global Error Handler

Handle all errors in one place:

Local Error Handling

Handle errors in specific middleware:

Error Boundaries

Create protected middleware sections:

Ignore Specific Errors

Silently handle expected errors:

Custom Error Classes

Create application-specific errors:

Error Logging

Log errors with context:

Best Practices

  1. Always set an error handler
  2. Handle specific errors explicitly
  3. Don’t leak sensitive information
  4. Implement retry logic for transient errors
  5. Fail gracefully
Proper error handling makes your bot robust and reliable!