fix: narrow exception handling and fix session leak in gift.py

- Replace broad `except Exception` with `except TelegramAPIError` in
  balance.py and wheel.py Stars invoice creation (prevents masking
  programming errors)
- Fix session leak in gift.py telegram_stars path: wrap PaymentService
  usage in try/finally to ensure bot.session.close() is called
This commit is contained in:
Fringg
2026-03-21 02:55:48 +03:00
parent 0a53b85b8a
commit 3875335cd7
3 changed files with 17 additions and 11 deletions
+2 -1
View File
@@ -269,6 +269,7 @@ async def create_stars_invoice(
# Create invoice through Telegram Bot API
try:
from aiogram.exceptions import TelegramAPIError
from aiogram.types import LabeledPrice
async with create_bot() as bot:
@@ -294,7 +295,7 @@ async def create_stars_invoice(
amount_kopeks=normalized_kopeks,
)
except Exception as e:
except TelegramAPIError as e:
logger.error('Error creating Stars invoice', error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+13 -9
View File
@@ -375,15 +375,19 @@ async def create_gift_purchase(
bot = create_bot()
payment_service = PaymentService(bot=bot)
payment_result = await payment_service.create_guest_payment(
db=db,
amount_kopeks=price_kopeks,
payment_method=body.payment_method,
description=f'Gift: {tariff.name} ({body.period_days}d)',
purchase_token=purchase.token,
return_url=return_url,
)
try:
payment_service = PaymentService(bot=bot)
payment_result = await payment_service.create_guest_payment(
db=db,
amount_kopeks=price_kopeks,
payment_method=body.payment_method,
description=f'Gift: {tariff.name} ({body.period_days}d)',
purchase_token=purchase.token,
return_url=return_url,
)
finally:
if bot:
await bot.session.close()
if payment_result is None:
await db.rollback()
+2 -1
View File
@@ -249,6 +249,7 @@ async def create_stars_invoice(
# Создаем invoice через Telegram Bot API
try:
from aiogram.exceptions import TelegramAPIError
from aiogram.types import LabeledPrice
from app.bot_factory import create_bot
@@ -270,7 +271,7 @@ async def create_stars_invoice(
stars_amount=stars_amount,
)
except Exception as e:
except TelegramAPIError as e:
logger.error('Error creating invoice', error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,