errors.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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], error_type: Optional[str] = None,
  20. message_override: Optional[str] = None) -> None:
  21. self.data = data
  22. msg = message_override or data["message"]
  23. if error_type:
  24. msg = f"{error_type}: {msg}"
  25. super().__init__(msg)
  26. class TimeoutException(ResponseError):
  27. pass
  28. class UnknownIdentityKey(ResponseError):
  29. pass
  30. class CaptchaRequired(ResponseError):
  31. pass
  32. class UserAlreadyExistsError(ResponseError):
  33. def __init__(self, data: Dict[str, Any]) -> None:
  34. super().__init__(data, message_override="You're already logged in")
  35. class RequestValidationFailure(ResponseError):
  36. def __init__(self, data: Dict[str, Any]) -> None:
  37. results = data["validationResults"]
  38. result_str = ", ".join(results) if isinstance(results, list) else str(results)
  39. super().__init__(data, message_override=result_str)
  40. response_error_types = {
  41. "invalid_request": RequestValidationFailure,
  42. "TimeoutException": TimeoutException,
  43. "UserAlreadyExists": UserAlreadyExistsError,
  44. "RequestValidationFailure": RequestValidationFailure,
  45. "UnknownIdentityKey": UnknownIdentityKey,
  46. "CaptchaRequired": CaptchaRequired,
  47. # TODO add rest from https://gitlab.com/signald/signald/-/tree/main/src/main/java/io/finn/signald/exceptions
  48. }
  49. def make_response_error(data: Dict[str, Any]) -> ResponseError:
  50. error_data = data["error"]
  51. if isinstance(error_data, str):
  52. error_data = {"message": error_data}
  53. elif not isinstance(error_data, dict):
  54. error_data = {"message": str(error_data)}
  55. if "message" not in error_data:
  56. error_data["message"] = "no message, see signald logs"
  57. error_type = data.get("error_type")
  58. try:
  59. error_class = response_error_types[error_type]
  60. except KeyError:
  61. return ResponseError(error_data, error_type=error_type)
  62. else:
  63. return error_class(error_data)