DEHuckaKpyT / telegram-bot

Kotlin Telegram Bot Library for creating scalable and expandable applications with helpful features.
https://dehuckakpyt.github.io/telegram-bot/starter-topic.html
Apache License 2.0
29 stars 3 forks source link

Suggestion: ExceptionHandler for callbacks. #12

Open DaLLr0g opened 4 days ago

DaLLr0g commented 4 days ago

It'd be really helpful to have a separate method for handling errors during handling callback queries. I've come up with a workaround wrapping my logic into try/catch and throwing my own exception with a callback ID, to execute method answerCallbackQuery, but having separate handler that is only for callbacks would make it much easier imo.

open class ExceptionHandlerImpl(
    protected val bot: TelegramBot,
    protected val template: MessageTemplate,
    templater: Templater,
) : ExceptionHandler, Templater by templater {

    private val logger = LoggerFactory.getLogger(javaClass)

    /*...
     other code
     ...*/

    /** something like that as u have for defaut `caught` but could be refactored =) */
    open suspend fun caught(callback: CallbackQuery, chat: Chat, ex: Throwable): Unit {
        when (ex) {
            is ChatException -> {
                bot.sendMessage(chat.id, template.whenKnownException with ("message" to ex.localizedMessage))
            }

            else -> {
                logger.error("Unexpected error while handling message in chat ${chat.id}", ex)
                bot.sendMessage(chat.id, template.whenUnknownException)
            }
        }
    }
}
DEHuckaKpyT commented 3 days ago

I have an idea how to do it. I'll try to do it during the week.

DEHuckaKpyT commented 3 days ago

You can look at the PR and tell me if that's an option for you.