refactor: global error handling

This commit is contained in:
vchikalkin 2025-09-12 13:58:26 +03:00
parent 7a08f968f4
commit 9a3b3d6bad
2 changed files with 28 additions and 32 deletions

View File

@ -13,44 +13,38 @@ const feature = composer.chatType('private');
const redis = getRedisInstance(); const redis = getRedisInstance();
feature.on('message:text', logHandle('download-message'), async (context) => { feature.on('message:text', logHandle('download-message'), async (context) => {
try { const url = context.message.text.trim();
const url = context.message.text.trim();
if (!validateTikTokUrl(url)) { if (!validateTikTokUrl(url)) {
return context.reply(context.t('err-invalid-url')); return context.reply(context.t('err-invalid-url'));
} }
const cachedFileId = await redis.get(url); const cachedFileId = await redis.get(url);
if (cachedFileId) { if (cachedFileId) {
return context.replyWithVideo(cachedFileId); return context.replyWithVideo(cachedFileId);
} }
const { message, result } = await Downloader(url, { version: 'v3' }); const { message, result } = await Downloader(url, { version: 'v3' });
if (message) { if (message) {
throw new Error(message); throw new Error(message);
} }
const videoUrl = result?.videoSD || result?.videoWatermark; const videoUrl = result?.videoSD || result?.videoWatermark;
const imagesUrls = result?.images; const imagesUrls = result?.images;
if (!videoUrl && !imagesUrls?.length) { if (!videoUrl && !imagesUrls?.length) {
return context.reply(context.t('err-invalid-download-urls')); return context.reply(context.t('err-invalid-download-urls'));
} }
if (result?.type === 'video' && videoUrl) { if (result?.type === 'video' && videoUrl) {
const { video } = await context.replyWithVideo(new InputFile({ url: videoUrl })); const { video } = await context.replyWithVideo(new InputFile({ url: videoUrl }));
await redis.set(url, video.file_id, 'EX', TTL_URLS); return redis.set(url, video.file_id, 'EX', TTL_URLS);
return; }
}
if (result?.type === 'image' && imagesUrls) { if (result?.type === 'image' && imagesUrls) {
return context.replyWithMediaGroup( return context.replyWithMediaGroup(
imagesUrls.map((image) => ({ media: image, type: 'photo' })), imagesUrls.map((image) => ({ media: image, type: 'photo' })),
); );
}
} catch (error) {
context.logger.error(error);
return context.reply(context.t('err-generic'));
} }
}); });

View File

@ -2,9 +2,11 @@ import { type Context } from '../context';
import { getUpdateInfo } from '../helpers/logging'; import { getUpdateInfo } from '../helpers/logging';
import { type ErrorHandler } from 'grammy'; import { type ErrorHandler } from 'grammy';
export const errorHandler: ErrorHandler<Context> = (error) => { export const errorHandler: ErrorHandler<Context> = async (error) => {
const { ctx } = error; const { ctx } = error;
await ctx.reply(ctx.t('err-generic'));
ctx.logger.error({ ctx.logger.error({
err: error.error, err: error.error,
update: getUpdateInfo(ctx), update: getUpdateInfo(ctx),