failure.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from functools import wraps
  2. from enum import Enum, auto
  3. from ..types import Message, Context, Response, CommandType
  4. class RollbotFailureException(BaseException):
  5. def __init__(self, failure):
  6. super().__init__()
  7. self.failure = failure
  8. class RollbotFailure(Enum):
  9. INVALID_COMMAND = auto()
  10. MISSING_SUBCOMMAND = auto()
  11. INVALID_SUBCOMMAND = auto()
  12. INVALID_ARGUMENTS = auto()
  13. SERVICE_DOWN = auto()
  14. PERMISSIONS = auto()
  15. INTERNAL_ERROR = auto()
  16. def get_debugging(self):
  17. debugging = {}
  18. reason = getattr(self, "reason", None)
  19. if reason is not None:
  20. debugging["explain"] = reason
  21. exception = getattr(self, "exception", None)
  22. if exception is not None:
  23. debugging["exception"] = exception
  24. return debugging
  25. def with_reason(self, reason):
  26. self.reason = reason
  27. return self
  28. def with_exception(self, exception):
  29. self.exception = exception
  30. return self
  31. def raise_exc(self):
  32. raise RollbotFailureException(self)
  33. def with_failure_handling(fn: CommandType) -> CommandType:
  34. @wraps(fn)
  35. async def wrapped(message: Message, context: Context):
  36. try:
  37. await fn()
  38. except RollbotFailureException as exc:
  39. # TODO handle errors more specifically
  40. await context.respond(Response.from_message(message, str(exc.failure)))
  41. return wrapped