feat(bot): add error handling middleware for telegram bot

Add onError middleware to handle and log errors gracefully, providing user feedback when errors occur
This commit is contained in:
Yuu Ottosoka
2025-07-11 14:03:03 +03:00
parent 084b100589
commit c0c04bbdba
2 changed files with 17 additions and 0 deletions

View File

@@ -6,10 +6,12 @@ import { logger } from '@repo/logger';
import { PrismaStorageAdapter } from './session-storage'; import { PrismaStorageAdapter } from './session-storage';
import { BotContext } from './types'; import { BotContext } from './types';
import { upsertUser } from './middlewares/upsert-user'; import { upsertUser } from './middlewares/upsert-user';
import { onError } from './middlewares/on-error';
const bot = new Bot<BotContext>(config.BOT_TOKEN); const bot = new Bot<BotContext>(config.BOT_TOKEN);
const storage = new PrismaStorageAdapter(); const storage = new PrismaStorageAdapter();
bot.use(onError);
bot.use(session({ storage, initial: () => ({}) })); bot.use(session({ storage, initial: () => ({}) }));
bot.use(upsertUser); bot.use(upsertUser);

View File

@@ -0,0 +1,15 @@
import { MiddlewareFn } from 'grammy';
import { BotContext } from '../types';
import { logger } from '@repo/logger';
const errorReply =
'Извините, произошла ошибка при обработке вашего запроса. Пожалуйста, попробуйте позже.';
const replyErrorLog = 'Не удалось отправить сообщение об ошибке пользователю';
export const onError: MiddlewareFn<BotContext> = async (ctx, next) => {
return await next().catch(async () => {
await ctx.reply(errorReply).catch((err) => {
logger.error(replyErrorLog, err);
});
});
};