Skip to content

[FAQ] handle exceptions during commands

Housa Hitomi edited this page May 23, 2023 · 3 revisions

demo:

from khl import Bot, Message
from khl.command import Command


@bot.command()
async def foo(m: Message, b: Bot):
    raise ValueError()


@foo.on_exception(ValueError)
async def bar(cmd: Command, e: ValueError, m: Message):
    print(f'a ValueError caught {e} while handling command {cmd.name} with {m.content}')

besides, you can catch built-in exceptions raised from command's internal process procedure, for example:

from khl.command import Command, Exceptions

@foo.on_exception(Exceptions.Handler.RuleNotPassed)
async def bar(cmd: Command, e: Exceptions.Handler.RuleNotPassed, m: Message):
    print(f'an Exceptions.Handler.RuleNotPassed caught {e} while handling command {cmd.name} with {m.content}')

this snippet handles RuleNotPassed exception, raised when some given rules not passed

for more built-in exception types, please turn to khl.command.Exceptions