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();
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)) {
return context.reply(context.t('err-invalid-url'));
}
if (!validateTikTokUrl(url)) {
return context.reply(context.t('err-invalid-url'));
}
const cachedFileId = await redis.get(url);
if (cachedFileId) {
return context.replyWithVideo(cachedFileId);
}
const cachedFileId = await redis.get(url);
if (cachedFileId) {
return context.replyWithVideo(cachedFileId);
}
const { message, result } = await Downloader(url, { version: 'v3' });
if (message) {
throw new Error(message);
}
const { message, result } = await Downloader(url, { version: 'v3' });
if (message) {
throw new Error(message);
}
const videoUrl = result?.videoSD || result?.videoWatermark;
const imagesUrls = result?.images;
const videoUrl = result?.videoSD || result?.videoWatermark;
const imagesUrls = result?.images;
if (!videoUrl && !imagesUrls?.length) {
return context.reply(context.t('err-invalid-download-urls'));
}
if (!videoUrl && !imagesUrls?.length) {
return context.reply(context.t('err-invalid-download-urls'));
}
if (result?.type === 'video' && videoUrl) {
const { video } = await context.replyWithVideo(new InputFile({ url: videoUrl }));
await redis.set(url, video.file_id, 'EX', TTL_URLS);
return;
}
if (result?.type === 'video' && videoUrl) {
const { video } = await context.replyWithVideo(new InputFile({ url: videoUrl }));
return redis.set(url, video.file_id, 'EX', TTL_URLS);
}
if (result?.type === 'image' && imagesUrls) {
return context.replyWithMediaGroup(
imagesUrls.map((image) => ({ media: image, type: 'photo' })),
);
}
} catch (error) {
context.logger.error(error);
return context.reply(context.t('err-generic'));
if (result?.type === 'image' && imagesUrls) {
return context.replyWithMediaGroup(
imagesUrls.map((image) => ({ media: image, type: 'photo' })),
);
}
});

View File

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