From 3194f13e12f4e8d71ad743ce2cd88cc9ff7b299e Mon Sep 17 00:00:00 2001 From: deptyped Date: Sat, 23 Sep 2023 18:39:10 +0300 Subject: [PATCH] Improve error handling Fixes an issue where an error was not handled if it occurred after the request processing was complete. --- src/bot/index.ts | 25 +++++++++++-------------- src/server/index.ts | 13 +++---------- 2 files changed, 14 insertions(+), 24 deletions(-) diff --git a/src/bot/index.ts b/src/bot/index.ts index 83770e11..74e1f53e 100644 --- a/src/bot/index.ts +++ b/src/bot/index.ts @@ -30,39 +30,36 @@ export function createBot(token: string, options: Options = {}) { ...options.config, ContextConstructor: createContextConstructor({ logger }), }); + const protectedBot = bot.errorBoundary(errorHandler); // Middlewares bot.api.config.use(parseMode("HTML")); if (config.isDev) { - bot.use(updateLogger()); + protectedBot.use(updateLogger()); } - bot.use(autoChatAction(bot.api)); - bot.use(hydrateReply); - bot.use(hydrate()); - bot.use( + protectedBot.use(autoChatAction(bot.api)); + protectedBot.use(hydrateReply); + protectedBot.use(hydrate()); + protectedBot.use( session({ initial: () => ({}), storage: sessionStorage, }), ); - bot.use(i18n); + protectedBot.use(i18n); // Handlers - bot.use(welcomeFeature); - bot.use(botAdminFeature); + protectedBot.use(welcomeFeature); + protectedBot.use(botAdminFeature); if (isMultipleLocales) { - bot.use(languageFeature); + protectedBot.use(languageFeature); } // must be the last handler - bot.use(unhandledFeature); - - if (config.isDev) { - bot.catch(errorHandler); - } + protectedBot.use(unhandledFeature); return bot; } diff --git a/src/server/index.ts b/src/server/index.ts index ff3ea7e4..a9591622 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -1,7 +1,6 @@ import fastify from "fastify"; -import { BotError, webhookCallback } from "grammy"; +import { webhookCallback } from "grammy"; import type { Bot } from "#root/bot/index.js"; -import { errorHandler } from "#root/bot/handlers/index.js"; import { logger } from "#root/logger.js"; export const createServer = async (bot: Bot) => { @@ -10,15 +9,9 @@ export const createServer = async (bot: Bot) => { }); server.setErrorHandler(async (error, request, response) => { - if (error instanceof BotError) { - errorHandler(error); + logger.error(error); - await response.code(200).send({}); - } else { - logger.error(error); - - await response.status(500).send({ error: "Oops! Something went wrong." }); - } + await response.status(500).send({ error: "Oops! Something went wrong." }); }); server.get("/", () => ({ status: true }));