1
0

exceptions.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. """Custom Exceptions."""
  2. from __future__ import annotations
  3. from typing import TYPE_CHECKING, Any
  4. if TYPE_CHECKING:
  5. from reflex.vars import Var
  6. class ReflexError(Exception):
  7. """Base exception for all Reflex exceptions."""
  8. class ConfigError(ReflexError):
  9. """Custom exception for config related errors."""
  10. class InvalidStateManagerModeError(ReflexError, ValueError):
  11. """Raised when an invalid state manager mode is provided."""
  12. class ReflexRuntimeError(ReflexError, RuntimeError):
  13. """Custom RuntimeError for Reflex."""
  14. class UploadTypeError(ReflexError, TypeError):
  15. """Custom TypeError for upload related errors."""
  16. class EnvVarValueError(ReflexError, ValueError):
  17. """Custom ValueError raised when unable to convert env var to expected type."""
  18. class ComponentTypeError(ReflexError, TypeError):
  19. """Custom TypeError for component related errors."""
  20. class ChildrenTypeError(ComponentTypeError):
  21. """Raised when the children prop of a component is not a valid type."""
  22. def __init__(self, component: str, child: Any):
  23. """Initialize the exception.
  24. Args:
  25. component: The name of the component.
  26. child: The child that caused the error.
  27. """
  28. super().__init__(
  29. f"Component {component} received child {child} of type {type(child)}. "
  30. "Accepted types are other components, state vars, or primitive Python types (dict excluded)."
  31. )
  32. class EventHandlerTypeError(ReflexError, TypeError):
  33. """Custom TypeError for event handler related errors."""
  34. class EventHandlerValueError(ReflexError, ValueError):
  35. """Custom ValueError for event handler related errors."""
  36. class StateValueError(ReflexError, ValueError):
  37. """Custom ValueError for state related errors."""
  38. class VarNameError(ReflexError, NameError):
  39. """Custom NameError for when a state var has been shadowed by a substate var."""
  40. class VarTypeError(ReflexError, TypeError):
  41. """Custom TypeError for var related errors."""
  42. class VarValueError(ReflexError, ValueError):
  43. """Custom ValueError for var related errors."""
  44. class VarAttributeError(ReflexError, AttributeError):
  45. """Custom AttributeError for var related errors."""
  46. class UntypedVarError(ReflexError, TypeError):
  47. """Custom TypeError for untyped var errors."""
  48. def __init__(self, var: Var, action: str, doc_link: str = ""):
  49. """Create an UntypedVarError from a var.
  50. Args:
  51. var: The var.
  52. action: The action that caused the error.
  53. doc_link: The link to the documentation.
  54. """
  55. var_data = var._get_all_var_data()
  56. is_state_var = (
  57. var_data
  58. and var_data.state
  59. and var_data.field_name
  60. and var_data.state + "." + var_data.field_name == str(var)
  61. )
  62. super().__init__(
  63. f"Cannot {action} on untyped var '{var!s}' of type '{var._var_type!s}'."
  64. + (
  65. " Please add a type annotation to the var in the state class."
  66. if is_state_var
  67. else " You can call the var's .to(desired_type) method to convert it to the desired type."
  68. )
  69. + (f" See {doc_link}" if doc_link else "")
  70. )
  71. class UntypedComputedVarError(ReflexError, TypeError):
  72. """Custom TypeError for untyped computed var errors."""
  73. def __init__(self, var_name: str):
  74. """Initialize the UntypedComputedVarError.
  75. Args:
  76. var_name: The name of the computed var.
  77. """
  78. super().__init__(f"Computed var '{var_name}' must have a type annotation.")
  79. class ComputedVarSignatureError(ReflexError, TypeError):
  80. """Custom TypeError for computed var signature errors."""
  81. def __init__(self, var_name: str, signature: str):
  82. """Initialize the ComputedVarSignatureError.
  83. Args:
  84. var_name: The name of the var.
  85. signature: The invalid signature.
  86. """
  87. super().__init__(f"Computed var `{var_name}{signature}` cannot take arguments.")
  88. class MissingAnnotationError(ReflexError, TypeError):
  89. """Custom TypeError for missing annotations."""
  90. def __init__(self, var_name: str):
  91. """Initialize the MissingAnnotationError.
  92. Args:
  93. var_name: The name of the var.
  94. """
  95. super().__init__(f"Var '{var_name}' must have a type annotation.")
  96. class UploadValueError(ReflexError, ValueError):
  97. """Custom ValueError for upload related errors."""
  98. class PageValueError(ReflexError, ValueError):
  99. """Custom ValueError for page related errors."""
  100. class RouteValueError(ReflexError, ValueError):
  101. """Custom ValueError for route related errors."""
  102. class VarOperationTypeError(ReflexError, TypeError):
  103. """Custom TypeError for when unsupported operations are performed on vars."""
  104. class VarDependencyError(ReflexError, ValueError):
  105. """Custom ValueError for when a var depends on a non-existent var."""
  106. class InvalidStylePropError(ReflexError, TypeError):
  107. """Custom Type Error when style props have invalid values."""
  108. class ImmutableStateError(ReflexError):
  109. """Raised when a background task attempts to modify state outside of context."""
  110. class LockExpiredError(ReflexError):
  111. """Raised when the state lock expires while an event is being processed."""
  112. class MatchTypeError(ReflexError, TypeError):
  113. """Raised when the return types of match cases are different."""
  114. class EventHandlerArgTypeMismatchError(ReflexError, TypeError):
  115. """Raised when the annotations of args accepted by an EventHandler differs from the spec of the event trigger."""
  116. class EventFnArgMismatchError(ReflexError, TypeError):
  117. """Raised when the number of args required by an event handler is more than provided by the event trigger."""
  118. class DynamicRouteArgShadowsStateVarError(ReflexError, NameError):
  119. """Raised when a dynamic route arg shadows a state var."""
  120. class ComputedVarShadowsStateVarError(ReflexError, NameError):
  121. """Raised when a computed var shadows a state var."""
  122. class ComputedVarShadowsBaseVarsError(ReflexError, NameError):
  123. """Raised when a computed var shadows a base var."""
  124. class EventHandlerShadowsBuiltInStateMethodError(ReflexError, NameError):
  125. """Raised when an event handler shadows a built-in state method."""
  126. class GeneratedCodeHasNoFunctionDefsError(ReflexError):
  127. """Raised when refactored code generated with flexgen has no functions defined."""
  128. class PrimitiveUnserializableToJSONError(ReflexError, ValueError):
  129. """Raised when a primitive type is unserializable to JSON. Usually with NaN and Infinity."""
  130. class InvalidLifespanTaskTypeError(ReflexError, TypeError):
  131. """Raised when an invalid task type is registered as a lifespan task."""
  132. class DynamicComponentMissingLibraryError(ReflexError, ValueError):
  133. """Raised when a dynamic component is missing a library."""
  134. class SetUndefinedStateVarError(ReflexError, AttributeError):
  135. """Raised when setting the value of a var without first declaring it."""
  136. class StateSchemaMismatchError(ReflexError, TypeError):
  137. """Raised when the serialized schema of a state class does not match the current schema."""
  138. class EnvironmentVarValueError(ReflexError, ValueError):
  139. """Raised when an environment variable is set to an invalid value."""
  140. class DynamicComponentInvalidSignatureError(ReflexError, TypeError):
  141. """Raised when a dynamic component has an invalid signature."""
  142. class InvalidPropValueError(ReflexError):
  143. """Raised when a prop value is invalid."""
  144. class StateTooLargeError(ReflexError):
  145. """Raised when the state is too large to be serialized."""
  146. class StateSerializationError(ReflexError):
  147. """Raised when the state cannot be serialized."""
  148. class StateMismatchError(ReflexError, ValueError):
  149. """Raised when the state retrieved does not match the expected state."""
  150. class SystemPackageMissingError(ReflexError):
  151. """Raised when a system package is missing."""
  152. def __init__(self, package: str):
  153. """Initialize the SystemPackageMissingError.
  154. Args:
  155. package: The missing package.
  156. """
  157. from reflex.constants import IS_MACOS
  158. extra = (
  159. f" You can do so by running 'brew install {package}'." if IS_MACOS else ""
  160. )
  161. super().__init__(
  162. f"System package '{package}' is missing."
  163. f" Please install it through your system package manager.{extra}"
  164. )
  165. class EventDeserializationError(ReflexError, ValueError):
  166. """Raised when an event cannot be deserialized."""
  167. class InvalidLockWarningThresholdError(ReflexError):
  168. """Raised when an invalid lock warning threshold is provided."""
  169. class UnretrievableVarValueError(ReflexError):
  170. """Raised when the value of a var is not retrievable."""