From a00f779460af02a8548b41a458e303b660b3a0b6 Mon Sep 17 00:00:00 2001 From: Kravets <57632712+kravetsone@users.noreply.github.com> Date: Sat, 17 Feb 2024 20:41:27 +0300 Subject: [PATCH] chore: add error handling topic in docs --- docs/.vitepress/config.mts | 1 + docs/error-handling/index.md | 56 ++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 docs/error-handling/index.md diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 38a2b97..80aea1d 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -81,6 +81,7 @@ export default defineConfig({ }, { text: "Formatting", link: "/formatting/index" }, { text: "Types", link: "/types/index" }, + { text: "Error Handling", link: "/error-handling/index" }, ], }, ], diff --git a/docs/error-handling/index.md b/docs/error-handling/index.md new file mode 100644 index 0000000..5886e7e --- /dev/null +++ b/docs/error-handling/index.md @@ -0,0 +1,56 @@ +# Error Handling + +It happens that errors occur in middleware and we need to handle them. +That's what the `onError` method was created for. + +```ts twoslash +import { Bot } from "gramio"; + +const bot = new Bot(""); +// ---cut--- + +bot.updates.on("message", () => { + bot.api.sendMessage({ + chat_id: "@not_found", + text: "Chat not exists....", + }); +}); + +bot.updates.onError(({ context, kind, error }) => { + if (context.is("message")) return context.send(`${kind}: ${error.message}`); +}); +``` + +## Errors + +### Telegram + +This error is the result of a failed request to the Telegram Bot API + +```ts twoslash +import { Bot } from "gramio"; + +const bot = new Bot(""); +// ---cut--- +bot.updates.onError(({ context, kind, error }) => { + if (kind === "TELEGRAM" && error.method === "sendMessage") { + error.params; // is sendMessage params + } +}); +``` + +### Unknown + +This error is any unknown error, whether it's your class or just an Error. + +```ts twoslash +import { Bot } from "gramio"; + +const bot = new Bot(""); +// ---cut--- +bot.updates.onError(({ context, kind, error }) => { + if (kind === "UNKNOWN") { + console.log(error.message); + } +}); +```