1515import time
1616import typing
1717import warnings
18- from collections .abc import AsyncIterator , Callable , Sequence
18+ from collections .abc import AsyncIterator , Callable , Iterator , Sequence
1919from enum import Enum
2020from hashlib import md5
2121from importlib .util import find_spec
3434 Event ,
3535 EventHandler ,
3636 EventSpec ,
37+ call_script ,
3738 fix_events ,
3839)
3940from reflex .istate import HANDLED_PICKLE_ERRORS , debug_failed_pickles
@@ -2473,8 +2474,17 @@ def wrapper() -> Component:
24732474class FrontendEventExceptionState (State ):
24742475 """Substate for handling frontend exceptions."""
24752476
2477+ # If the frontend error message contains any of these strings, automatically reload the page.
2478+ auto_reload_on_errors : ClassVar [list [str ]] = [
2479+ "TypeError: Cannot read properties of null" ,
2480+ ]
2481+ # Reload the page only once per cooldown period to avoid reload loops.
2482+ auto_reload_cooldown_time_ms : ClassVar [int ] = 10000
2483+
24762484 @event
2477- def handle_frontend_exception (self , info : str , component_stack : str ) -> None :
2485+ def handle_frontend_exception (
2486+ self , info : str , component_stack : str
2487+ ) -> Iterator [EventSpec ]:
24782488 """Handle frontend exceptions.
24792489
24802490 If a frontend exception handler is provided, it will be called.
@@ -2484,7 +2494,18 @@ def handle_frontend_exception(self, info: str, component_stack: str) -> None:
24842494 info: The exception information.
24852495 component_stack: The stack trace of the component where the exception occurred.
24862496
2497+ Yields:
2498+ Optional auto-reload event for certain errors outside cooldown period.
24872499 """
2500+ # Handle automatic reload for certain errors.
2501+ if type (self ).auto_reload_on_errors and any (
2502+ error in info for error in type (self ).auto_reload_on_errors
2503+ ):
2504+ yield call_script (
2505+ "const last_reload = parseInt(window.sessionStorage.getItem('reflex_last_reloaded_on_error')) || 0;"
2506+ f"if (Date.now() - last_reload > { type (self ).auto_reload_cooldown_time_ms } )"
2507+ "{window.sessionStorage.setItem('reflex_last_reloaded_on_error', Date.now().toString()); window.location.reload(true);}"
2508+ )
24882509 prerequisites .get_and_validate_app ().app .frontend_exception_handler (
24892510 Exception (info )
24902511 )
0 commit comments