exceptions.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from typing import Any, Type, Optional, Set, Dict
  2. def _name(type_: Type) -> str:
  3. return type_.__name__ if hasattr(type_, "__name__") else str(type_)
  4. class DaciteError(Exception):
  5. pass
  6. class DaciteFieldError(DaciteError):
  7. def __init__(self, field_path: Optional[str] = None):
  8. super().__init__()
  9. self.field_path = field_path
  10. def update_path(self, parent_field_path: str) -> None:
  11. if self.field_path:
  12. self.field_path = f"{parent_field_path}.{self.field_path}"
  13. else:
  14. self.field_path = parent_field_path
  15. class WrongTypeError(DaciteFieldError):
  16. def __init__(self, field_type: Type, value: Any, field_path: Optional[str] = None) -> None:
  17. super().__init__(field_path=field_path)
  18. self.field_type = field_type
  19. self.value = value
  20. def __str__(self) -> str:
  21. return (
  22. f'wrong value type for field "{self.field_path}" - should be "{_name(self.field_type)}" '
  23. f'instead of value "{self.value}" of type "{_name(type(self.value))}"'
  24. )
  25. class MissingValueError(DaciteFieldError):
  26. def __init__(self, field_path: Optional[str] = None):
  27. super().__init__(field_path=field_path)
  28. def __str__(self) -> str:
  29. return f'missing value for field "{self.field_path}"'
  30. class UnionMatchError(WrongTypeError):
  31. def __str__(self) -> str:
  32. return (
  33. f'can not match type "{_name(type(self.value))}" to any type '
  34. f'of "{self.field_path}" union: {_name(self.field_type)}'
  35. )
  36. class StrictUnionMatchError(DaciteFieldError):
  37. def __init__(self, union_matches: Dict[Type, Any], field_path: Optional[str] = None) -> None:
  38. super().__init__(field_path=field_path)
  39. self.union_matches = union_matches
  40. def __str__(self) -> str:
  41. conflicting_types = ", ".join(_name(type_) for type_ in self.union_matches)
  42. return f'can not choose between possible Union matches for field "{self.field_path}": {conflicting_types}'
  43. class ForwardReferenceError(DaciteError):
  44. def __init__(self, message: str) -> None:
  45. super().__init__()
  46. self.message = message
  47. def __str__(self) -> str:
  48. return f"can not resolve forward reference: {self.message}"
  49. class UnexpectedDataError(DaciteError):
  50. def __init__(self, keys: Set[str]) -> None:
  51. super().__init__()
  52. self.keys = keys
  53. def __str__(self) -> str:
  54. formatted_keys = ", ".join(f'"{key}"' for key in self.keys)
  55. return f"can not match {formatted_keys} to any data class field"