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:
@@ -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);
|
||||||
|
|
||||||
|
|||||||
15
apps/bot/src/middlewares/on-error.ts
Normal file
15
apps/bot/src/middlewares/on-error.ts
Normal 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user