errors.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Copyright (c) 2020 Tulir Asokan
  2. #
  3. # This Source Code Form is subject to the terms of the Mozilla Public
  4. # License, v. 2.0. If a copy of the MPL was not distributed with this
  5. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. from typing import Any, Dict, Optional
  7. class RPCError(Exception):
  8. pass
  9. class UnexpectedError(RPCError):
  10. pass
  11. class UnexpectedResponse(RPCError):
  12. def __init__(self, resp_type: str, data: Any) -> None:
  13. super().__init__(f"Got unexpected response type {resp_type}")
  14. self.resp_type = resp_type
  15. self.data = data
  16. class NotConnected(RPCError):
  17. pass
  18. class ResponseError(RPCError):
  19. def __init__(self, data: Dict[str, Any], message_override: Optional[str] = None) -> None:
  20. self.data = data
  21. super().__init__(message_override or data["message"])
  22. class UnknownResponseError(ResponseError):
  23. def __init__(self, message: str) -> None:
  24. self.data = {}
  25. super(RPCError, self).__init__(message)
  26. class InvalidRequest(ResponseError):
  27. def __init__(self, data: Dict[str, Any]) -> None:
  28. super().__init__(data, ", ".join(data.get("validationResults", "")))
  29. class TimeoutException(ResponseError):
  30. pass
  31. class UserAlreadyExistsError(ResponseError):
  32. def __init__(self, data: Dict[str, Any]) -> None:
  33. super().__init__(data, message_override="You're already logged in")
  34. response_error_types = {
  35. "invalid_request": InvalidRequest,
  36. "TimeoutException": TimeoutException,
  37. "UserAlreadyExists": UserAlreadyExistsError,
  38. }
  39. def make_response_error(data: Dict[str, Any]) -> ResponseError:
  40. if isinstance(data, str):
  41. return UnknownResponseError(data)
  42. return response_error_types.get(data["type"], ResponseError)(data)