console.error instead of raising Exception

This commit is contained in:
Lendemor 2025-01-14 22:58:22 +01:00
parent bc66f3f876
commit 4ab29edf98
6 changed files with 16 additions and 82 deletions

View File

@ -39,11 +39,7 @@ from typing_extensions import (
from reflex import constants from reflex import constants
from reflex.constants.state import FRONTEND_EVENT_STATE from reflex.constants.state import FRONTEND_EVENT_STATE
from reflex.utils import console, format from reflex.utils import console, format
from reflex.utils.exceptions import ( from reflex.utils.exceptions import EventFnArgMismatch, EventHandlerArgTypeMismatch
EventFnArgMismatch,
EventHandlerArgTypeMismatch,
VarAnnotationError,
)
from reflex.utils.types import ArgsSpec, GenericType, typehint_issubclass from reflex.utils.types import ArgsSpec, GenericType, typehint_issubclass
from reflex.vars import VarData from reflex.vars import VarData
from reflex.vars.base import LiteralVar, Var from reflex.vars.base import LiteralVar, Var
@ -1352,15 +1348,12 @@ def resolve_annotation(annotations: dict[str, Any], arg_name: str):
annotations: The annotations. annotations: The annotations.
arg_name: The argument name. arg_name: The argument name.
Raises:
VarAnnotationError: If the annotation is not found.
Returns: Returns:
The resolved annotation. The resolved annotation.
""" """
annotation = annotations.get(arg_name) annotation = annotations.get(arg_name)
if annotation is None: if annotation is None:
raise VarAnnotationError(arg_name, annotation) console.error(f"Invalid annotation '{annotation}' for var '{arg_name}'.")
return annotation return annotation

View File

@ -102,7 +102,6 @@ from reflex.utils.exceptions import (
InvalidLockWarningThresholdError, InvalidLockWarningThresholdError,
InvalidStateManagerMode, InvalidStateManagerMode,
LockExpiredError, LockExpiredError,
MismatchedArgumentTypeError,
ReflexRuntimeError, ReflexRuntimeError,
SetUndefinedStateVarError, SetUndefinedStateVarError,
StateSchemaMismatchError, StateSchemaMismatchError,
@ -1305,7 +1304,6 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
Raises: Raises:
SetUndefinedStateVarError: If a value of a var is set without first defining it. SetUndefinedStateVarError: If a value of a var is set without first defining it.
MismatchedArgumentTypeError: If the value of a var is not of the correct type.
""" """
if isinstance(value, MutableProxy): if isinstance(value, MutableProxy):
# unwrap proxy objects when assigning back to the state # unwrap proxy objects when assigning back to the state
@ -1343,10 +1341,9 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
if field.allow_none and not is_optional(field_type): if field.allow_none and not is_optional(field_type):
field_type = Union[field_type, None] field_type = Union[field_type, None]
if not _isinstance(value, field_type): if not _isinstance(value, field_type):
raise MismatchedArgumentTypeError( console.error(
value, f"Expected field '{type(self).__name__}.{name}' to receive type '{field_type}',"
f"{type(self).__name__}.{name}", f" but got '{value}' of type '{type(value)}'."
field_type,
) )
# Set the attribute. # Set the attribute.

View File

@ -59,53 +59,6 @@ class VarAttributeError(ReflexError, AttributeError):
"""Custom AttributeError for var related errors.""" """Custom AttributeError for var related errors."""
class VarAnnotationError(ReflexError, TypeError):
"""Custom AttributeError for var annotation related errors."""
def __init__(self, var_name, annotation_value):
"""Initialize the VarAnnotationError.
Args:
var_name: The name of the var.
annotation_value: The value of the annotation.
"""
super().__init__(
f"Invalid annotation '{annotation_value}' for var '{var_name}'."
)
class MismatchedArgumentTypeError(ReflexError, TypeError):
"""Custom TypeError for mismatched argument type errors."""
def __init__(self, value, field_name, expected_type):
"""Initialize the MismatchedArgumentError.
Args:
value: The name of the argument received.
field_name: The expected argument name.
expected_type: The expected argument type.
"""
super().__init__(
f"Expected field '{field_name}' to receive type '{expected_type}', but got '{value}' of type '{type(value)}'."
)
class MismatchedComputedVarReturn(ReflexError, TypeError):
"""Custom TypeError for mismatched computed var return type errors."""
def __init__(self, var_name, return_type, expected_type):
"""Initialize the MismatchedComputedVarReturn.
Args:
var_name: The name of the computed var.
return_type: The return type of the computed var.
expected_type: The expected return type.
"""
super().__init__(
f"Computed var '{var_name}' must return type '{expected_type}', got '{return_type}'."
)
class UntypedComputedVarError(ReflexError, TypeError): class UntypedComputedVarError(ReflexError, TypeError):
"""Custom TypeError for untyped computed var errors.""" """Custom TypeError for untyped computed var errors."""

View File

@ -45,7 +45,6 @@ from reflex.base import Base
from reflex.constants.compiler import Hooks from reflex.constants.compiler import Hooks
from reflex.utils import console, exceptions, imports, serializers, types from reflex.utils import console, exceptions, imports, serializers, types
from reflex.utils.exceptions import ( from reflex.utils.exceptions import (
MismatchedComputedVarReturn,
UntypedComputedVarError, UntypedComputedVarError,
VarAttributeError, VarAttributeError,
VarDependencyError, VarDependencyError,
@ -2014,9 +2013,6 @@ class ComputedVar(Var[RETURN_TYPE]):
instance: the instance of the class accessing this computed var. instance: the instance of the class accessing this computed var.
owner: the class that this descriptor is attached to. owner: the class that this descriptor is attached to.
Raises:
MismatchedComputedVarReturn: If the return type of the getter function does not match the var type.
Returns: Returns:
The value of the var for the given instance. The value of the var for the given instance.
""" """
@ -2052,11 +2048,11 @@ class ComputedVar(Var[RETURN_TYPE]):
value = getattr(instance, self._cache_attr) value = getattr(instance, self._cache_attr)
if not _isinstance(value, self._var_type): if not _isinstance(value, self._var_type):
raise MismatchedComputedVarReturn( console.error(
var_name=f"{type(instance).__name__}.{self._js_expr}", f"Computed var '{type(instance).__name__}.{self._js_expr}' must return"
return_type=type(value), f" type '{self._var_type}', got '{type(value)}'."
expected_type=self._var_type,
) )
return value return value
def _deps( def _deps(

View File

@ -33,7 +33,7 @@ def ClientSide():
class ClientSideSubState(ClientSideState): class ClientSideSubState(ClientSideState):
# cookies with default settings # cookies with default settings
c1: str = rx.Cookie() c1: str = rx.Cookie()
c2: rx.Cookie = "c2 default" # type: ignore c2: str = rx.Cookie("c2 default")
# cookies with custom settings # cookies with custom settings
c3: str = rx.Cookie(max_age=2) # expires after 2 second c3: str = rx.Cookie(max_age=2) # expires after 2 second
@ -44,7 +44,7 @@ def ClientSide():
# local storage with default settings # local storage with default settings
l1: str = rx.LocalStorage() l1: str = rx.LocalStorage()
l2: rx.LocalStorage = "l2 default" # type: ignore l2: str = rx.LocalStorage("l2 default")
# local storage with custom settings # local storage with custom settings
l3: str = rx.LocalStorage(name="l3") l3: str = rx.LocalStorage(name="l3")
@ -56,7 +56,7 @@ def ClientSide():
# Session storage # Session storage
s1: str = rx.SessionStorage() s1: str = rx.SessionStorage()
s2: rx.SessionStorage = "s2 default" # type: ignore s2: str = rx.SessionStorage("s2 default")
s3: str = rx.SessionStorage(name="s3") s3: str = rx.SessionStorage(name="s3")
def set_l6(self, my_param: str): def set_l6(self, my_param: str):
@ -87,13 +87,13 @@ def ClientSide():
rx.input( rx.input(
placeholder="state var", placeholder="state var",
value=ClientSideState.state_var, value=ClientSideState.state_var,
on_change=ClientSideState.set_state_var, # type: ignore on_change=ClientSideState.setvar("state_var"),
id="state_var", id="state_var",
), ),
rx.input( rx.input(
placeholder="input value", placeholder="input value",
value=ClientSideState.input_value, value=ClientSideState.input_value,
on_change=ClientSideState.set_input_value, # type: ignore on_change=ClientSideState.setvar("input_value"),
id="input_value", id="input_value",
), ),
rx.button( rx.button(

View File

@ -27,11 +27,7 @@ from reflex.event import (
from reflex.state import BaseState from reflex.state import BaseState
from reflex.style import Style from reflex.style import Style
from reflex.utils import imports from reflex.utils import imports
from reflex.utils.exceptions import ( from reflex.utils.exceptions import EventFnArgMismatch, EventHandlerArgTypeMismatch
EventFnArgMismatch,
EventHandlerArgTypeMismatch,
VarAnnotationError,
)
from reflex.utils.imports import ImportDict, ImportVar, ParsedImportDict, parse_imports from reflex.utils.imports import ImportDict, ImportVar, ParsedImportDict, parse_imports
from reflex.vars import VarData from reflex.vars import VarData
from reflex.vars.base import LiteralVar, Var from reflex.vars.base import LiteralVar, Var
@ -849,7 +845,6 @@ def test_component_event_trigger_arbitrary_args():
"on_foo": on_foo_spec, "on_foo": on_foo_spec,
} }
with pytest.raises(VarAnnotationError):
C1.create(on_foo=C1State.mock_handler) C1.create(on_foo=C1State.mock_handler)