Error Handling & API Resiliency
Relevant source files
The following files were used as context for generating this wiki page:
Introduction
The GentelmeN-CorE system implements a robust error handling and resiliency strategy designed to maintain bot uptime and provide graceful degradation when external dependencies fail. Given its reliance on multiple third-party APIs (Groq, KuCoin, Brave Search, Hugging Face, GitHub) and a PostgreSQL database, the architecture prioritizes "fail-fast" initialization for critical components and "soft-fail" patterns for non-essential features.
The primary goal is to ensure that a failure in one subsystem—such as a crypto ticker timeout or a database connection drop—does not crash the entire Telegram polling process. This is achieved through a combination of global exception catch blocks, specialized timeout configurations, and a restart policy managed by the deployment environment.
Sources: core/bot.py:14-25, core/integrations.py:11-50, railway.json:11-15
Core Resilience Architecture
Telegram Polling Loop
The main entry point utilizes an infinite loop surrounding the bot.infinity_polling method. If an unhandled exception occurs during the polling process (e.g., network instability), the system logs the crash, waits for a cooling period of 15 seconds, and then attempts to resume operation.
The diagram shows the self-healing nature of the Telegram connection handler.
Sources: core/bot.py:84-89
Fail-Fast Initialization
The system enforces strict validation of mandatory environment variables during the boot sequence. If essential tokens are missing, the application raises a RuntimeError, preventing the bot from entering a semi-functional state that would lead to confusing runtime errors.
| Component | Variable | Criticality | Logic on Failure |
|---|---|---|---|
| Telegram Bot | TELEGRAM_TOKEN | High | RuntimeError (Abort) |
| Groq AI | GROQ_KEY | High | RuntimeError (Abort) |
| KuCoin API | KUCOIN_API_KEY | Medium | Sets kucoin = None |
| Database | DATABASE_URL | Medium | Defaults to local cache / skips DB ops |
Sources: core/bot.py:14-23, core/database.py:13-15
API Integration Resiliency
Timeout and Request Management
All external API calls made via the requests library are protected by explicit timeouts to prevent the bot's execution threads from hanging indefinitely.
- Brave Search: Uses a 5-second timeout and returns an empty string on
RequestExceptionor HTTP errors. - Hugging Face (Image Generation): Uses a 30-second timeout due to the intensive nature of the
FLUX.1-schnellmodel. It handles specificrequests.Timeoutexceptions separately to provide user-friendly feedback. - GitHub API: Uses a 10-second timeout within the command handler.
Sources: core/integrations.py:15-18, core/integrations.py:40-48, core/commands.py:182-185
Image Generation Error States
The Hugging Face integration returns a tuple (image, error). This pattern allows the calling function to distinguish between a successful byte stream and various failure modes (missing tokens, 503 Service Unavailable, or timeouts).
The flow demonstrates how specialized error messages are propagated back to the user.
Sources: core/integrations.py:33-50
Database & Persistence Stability
Graceful Database Degradation
The core/database.py module is designed to function even if DATABASE_URL is not provided or the connection fails. In such cases, the system falls back to default settings (English language, Llama-3.3 model) and utilizes in-memory dictionaries (user_prefs, user_models) as a temporary cache.
def get_user_data(user_id):
if user_id in user_prefs and user_id in user_models:
return user_prefs[user_id], user_models[user_id]
if not DB_URL:
return 'EN', 'llama-3.3-70b-versatile'
try:
with psycopg2.connect(DB_URL) as conn:
# Database logic...
except Exception as e:
logging.warning(f"DB error: {e}")
return 'EN', 'llama-3.3-70b-versatile'
Sources: core/database.py:35-56
Async Price Monitor Safety
The price_monitor runs in a daemon thread. It includes a try-except block within its infinite loop to ensure that a transient database failure or a KuCoin API error does not terminate the background monitoring thread. It specifically checks for both kucoin and DB_URL availability before each iteration.
Sources: core/bot.py:46-49, core/bot.py:78-79
Deployment Resiliency
The project configuration in railway.json specifies a restart policy to handle catastrophic process failures that escape the Python-level try-except blocks.
- Restart Policy:
ON_FAILURE - Max Retries: 10
- Health Delay: The bot includes a
time.sleep(15)at startup to allow the deployment environment (Railway) to successfully shut down old instances and release resources before the new instance begins polling.
Sources: railway.json:11-15, core/bot.py:82
Conclusion
GentelmeN-CorE achieves resiliency by isolating external failures. By wrapping API calls in specific exception handlers and providing fallback values for database and integration services, the system maintains a high level of availability for its core Telegram interface. The combination of Python-level error handling and environment-level restart policies ensures a multi-layered defense against downtime.