Skip to content

Commit

Permalink
Improve error handling
Browse files Browse the repository at this point in the history
Fixes an issue where an error was not handled if it occurred after the request processing was complete.
  • Loading branch information
deptyped committed Sep 23, 2023
1 parent ed61922 commit 3194f13
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 24 deletions.
25 changes: 11 additions & 14 deletions src/bot/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
13 changes: 3 additions & 10 deletions src/server/index.ts
Original file line number Diff line number Diff line change
@@ -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) => {
Expand All @@ -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 }));
Expand Down

0 comments on commit 3194f13

Please sign in to comment.