error_handling.py 1.4 KB

123456789101112131415161718192021222324252627282930
  1. from functools import wraps
  2. from ..types import Message, Context, Response, CommandType
  3. from ..failure import RollbotFailure, RollbotFailureException
  4. explanations = {
  5. RollbotFailure.INVALID_COMMAND: "Sorry - I don't think I understand the command '!{}'... I'll try to figure it out and get back to you!",
  6. RollbotFailure.MISSING_SUBCOMMAND: "Sorry - !{} requires a sub-command.",
  7. RollbotFailure.INVALID_SUBCOMMAND: "Sorry - the sub-command you used for {} was not valid.",
  8. RollbotFailure.INVALID_ARGUMENTS: "Sorry - !{} cannot use those arguments!",
  9. RollbotFailure.SERVICE_DOWN: "Sorry - !{} relies on a service I couldn't reach!",
  10. RollbotFailure.PERMISSIONS: "Sorry - you don't have permission to use that command or sub-command in this chat!",
  11. RollbotFailure.INTERNAL_ERROR: "Sorry - I encountered an unrecoverable error, please review internal logs.",
  12. }
  13. def with_failure_handling(fn: CommandType) -> CommandType:
  14. @wraps(fn)
  15. async def wrapped(message: Message, context: Context):
  16. try:
  17. await fn(message, context)
  18. except RollbotFailureException as exc:
  19. explanation = explanations[exc.failure]
  20. if "{}" in explanation:
  21. explanation = explanation.format(message.command.name)
  22. if exc.detail is not None:
  23. explanation += " " + exc.detail
  24. await context.respond(Response.from_message(message, explanation))
  25. return wrapped