Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

exception handler draft #1

Draft
wants to merge 14 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions reflex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@
"EventChain",
"background",
"call_script",
"client_error",
"clear_local_storage",
"console_log",
"download",
Expand Down
15 changes: 15 additions & 0 deletions reflex/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,12 @@ class App(Base):
# The radix theme for the entire app
theme: Optional[Component] = themes.theme(accent_color="blue")

# Custom exception handler
exception_handler: Optional[Callable] = None

# client-side exception handler on error
load_error_handler: Optional[Callable] = None

def __init__(self, *args, **kwargs):
"""Initialize the app.

Expand Down Expand Up @@ -391,6 +397,10 @@ def add_page(
| None = None,
meta: list[dict[str, str]] = constants.DefaultPage.META_LIST,
script_tags: list[Component] | None = None,
on_error: EventHandler
| EventSpec
| list[EventHandler | EventSpec]
| None = None,
):
"""Add a page to the app.

Expand Down Expand Up @@ -464,6 +474,11 @@ def add_page(
if not isinstance(on_load, list):
on_load = [on_load]
self.load_events[route] = on_load

if on_error:
self.load_error_handler = on_error



def get_load_events(self, route: str) -> list[EventHandler | EventSpec]:
"""Get the load events for a route.
Expand Down
31 changes: 26 additions & 5 deletions reflex/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from reflex import constants
from reflex.base import Base
from reflex.utils import console, format
from reflex.utils import console, format, prerequisites
from reflex.utils.types import ArgsSpec
from reflex.vars import BaseVar, Var

Expand Down Expand Up @@ -666,13 +666,34 @@ def call_script(
callback_kwargs = {
"callback": f"({arg_name}) => queueEvents([{format.format_event(event_spec)}], {constants.CompileVars.SOCKET})"
}

error_event_spec = client_error('client error')

wrapped_code = f"""

This comment was marked as resolved.

try {{
{javascript_code}
}} catch (e) {{
queueEvents([{format.format_event(error_event_spec)}], {constants.CompileVars.SOCKET})
}}
"""
return server_side(
"_call_script",
get_fn_signature(call_script),
javascript_code=wrapped_code,
**callback_kwargs,
)

def client_error(error: Any) -> EventSpec:
return server_side(
"_call_script",
get_fn_signature(call_script),
javascript_code=javascript_code,
**callback_kwargs,
"_client_error",
get_fn_signature(client_error),
error = error
)

def client_error_handler(): # just for test
app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
exception_handler = app.load_error_handler
return exception_handler

def get_event(state, event):
"""Get the event from the given state.
Expand Down
7 changes: 6 additions & 1 deletion reflex/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -1192,7 +1192,12 @@ async def _process_event(
# If an error occurs, throw a window alert.
except Exception:
error = traceback.format_exc()
print(error)
app = getattr(prerequisites.get_app(), constants.CompileVars.APP)
exception_handler = app.exception_handler
if callable(exception_handler):
exception_handler(error)
else:
print(error)
yield state._as_state_update(
handler,
window_alert("An error occurred. See logs for details."),
Expand Down
3 changes: 3 additions & 0 deletions tests/states/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ def go(self, c: int):
Yields:
After each increment.
"""
if c < 0:
raise ValueError("Test exception")

for _ in range(c):
self.value += 1
yield
18 changes: 18 additions & 0 deletions tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -1131,6 +1131,24 @@ async def test_process_events(mocker, token: str):
await app.state_manager.close()


@pytest.mark.asyncio
async def test_custom_exception_handler():

def custom_exception_handler(exception):
print(f"custom exception handler called: {exception}")

app = App(state=GenState, exception_handler=custom_exception_handler)
event = Event(
token="t",
name="gen_state.go",
payload={"c": -1},
)

with pytest.raises(ValueError, match="Test exception"):
async for _update in app.process(event, "mock_sid", {}, "127.0.0.1"):
pass


@pytest.mark.parametrize(
("state", "overlay_component", "exp_page_child"),
[
Expand Down