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 withbot.catch():
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: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
Related
- Bot - Bot error handler setup
- Middleware - Error boundaries
- Context - Context in error handlers