error_boundary.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """A React Error Boundary component that catches unhandled frontend exceptions."""
  2. from __future__ import annotations
  3. from typing import List
  4. from reflex.compiler.compiler import _compile_component
  5. from reflex.components.component import Component
  6. from reflex.components.el import div, p
  7. from reflex.constants import Hooks, Imports
  8. from reflex.event import EventChain, EventHandler
  9. from reflex.ivars.base import ImmutableVar
  10. from reflex.ivars.function import FunctionVar
  11. from reflex.utils.imports import ImportVar
  12. from reflex.vars import Var
  13. class ErrorBoundary(Component):
  14. """A React Error Boundary component that catches unhandled frontend exceptions."""
  15. library = "react-error-boundary"
  16. tag = "ErrorBoundary"
  17. # Fired when the boundary catches an error.
  18. on_error: EventHandler[lambda error, info: [error, info]] = ImmutableVar( # type: ignore
  19. "logFrontendError"
  20. ).to(FunctionVar, EventChain)
  21. # Rendered instead of the children when an error is caught.
  22. Fallback_component: Var[Component] = ImmutableVar.create_safe("Fallback")._replace(
  23. _var_type=Component
  24. )
  25. def add_imports(self) -> dict[str, list[ImportVar]]:
  26. """Add imports for the component.
  27. Returns:
  28. The imports to add.
  29. """
  30. return Imports.EVENTS
  31. def add_hooks(self) -> List[str | ImmutableVar]:
  32. """Add hooks for the component.
  33. Returns:
  34. The hooks to add.
  35. """
  36. return [Hooks.EVENTS, Hooks.FRONTEND_ERRORS]
  37. def add_custom_code(self) -> List[str]:
  38. """Add custom Javascript code into the page that contains this component.
  39. Custom code is inserted at module level, after any imports.
  40. Returns:
  41. The custom code to add.
  42. """
  43. fallback_container = div(
  44. p("Ooops...Unknown Reflex error has occured:"),
  45. p(
  46. ImmutableVar.create("error.message"),
  47. color="red",
  48. ),
  49. p("Please contact the support."),
  50. )
  51. compiled_fallback = _compile_component(fallback_container)
  52. return [
  53. f"""
  54. function Fallback({{ error, resetErrorBoundary }}) {{
  55. return (
  56. {compiled_fallback}
  57. );
  58. }}
  59. """
  60. ]
  61. error_boundary = ErrorBoundary.create