Coverage for src / lexigram / ui / molecules / error_boundary.py: 100%

19 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-08-10 04:11 +0800

1"""Error Boundary component for Lexigram Admin.""" 

2 

3from __future__ import annotations 

4 

5from typing import Any 

6 

7from lexigram.logging import get_logger 

8from lexigram.ui.core.base import Component, el, render_to_string 

9from lexigram.ui.molecules.error_state import ErrorState 

10 

11logger = get_logger(__name__) 

12 

13 

14class ErrorBoundary(Component): 

15 """Component that catches rendering errors in its children. 

16 

17 This provides a fallback UI when a sub-component fails to render, 

18 preventing the entire page from breaking. 

19 """ 

20 

21 def __init__(self, fallback: Any | None = None, **props) -> None: 

22 super().__init__(**props) 

23 self.fallback = fallback 

24 

25 def render(self) -> Any: 

26 try: 

27 # Force rendering of children to catch exceptions early 

28 content = render_to_string(self.children) 

29 return el("div", content, **self.props) 

30 except Exception as e: # error boundary must catch all rendering errors 

31 logger.exception("Error rendering component inside ErrorBoundary") 

32 if self.fallback: 

33 return el("div", self.fallback, role="alert") 

34 

35 return el( 

36 "div", 

37 ErrorState( 

38 title="Rendering Error", 

39 message=f"A component failed to display: {e!s}", 

40 action=el( 

41 "button", 

42 "Reload Page", 

43 onclick="window.location.reload()", 

44 class_="px-4 py-2 bg-destructive text-destructive-foreground rounded hover:bg-destructive/90 transition-colors", 

45 ), 

46 ), 

47 role="alert", 

48 )