pysxLearn by building

Runtime and resilience · Lesson 18 of 28

Error boundaries and retry

Recover one failed region without discarding healthy sibling state.

A local failure should have a local recovery boundary when the rest of the interface can still work. ErrorBoundary owns its content and a fallback. A failure retires the affected region instead of exposing a traceback to the page.

ErrorInfo is deliberately redacted. It provides a safe message and correlation identity, while the cause stays in server diagnostics. Retry recreates the failed subtree; it does not undo an already committed business operation.

Understand the moving parts

Keep a healthy sibling outside the boundary. That makes the recovery scope observable: if its draft or count vanishes, the implementation reset too much. A component's local state may correctly restart when its own failed lifetime ends.

The live panel throws a real handler error. Use the sibling while the fallback is visible, then retry. The fallback's retry callback is owned by the current boundary generation and should not revive an older discarded instance.

Walk through the code

from collections.abc import Callable
from pysx import ErrorBoundary, ErrorInfo, Fragment, local_state, pysx, signal


def app() -> Fragment:
    sibling = signal(0)

    def content() -> Fragment:
        count = local_state("count", 0)

        def fail(_: object) -> None:
            raise ValueError("intentional lesson boundary failure")

        return pysx(t"""
            section(id="boundary-content")
                p: "Healthy local panel"
                output(id="boundary-count"): {count}
                button(id="boundary-fail" onClick={fail}): "Fail this panel"
        """)

    def fallback(info: ErrorInfo, retry: Callable[[], None]) -> Fragment:
        def reset(_: object) -> None:
            retry()

        return pysx(t"""
            section(id="boundary-fallback" role="alert")
                p: {info.message}
                button(id="boundary-retry" onClick={reset}): "Retry panel"
        """)

    Boundary = ErrorBoundary(content, fallback)

    def increment(_: object) -> None:
        sibling.update(lambda value: value + 1)

    return pysx(t"""
        Boundary:
        button(id="sibling-increment" onClick={increment}): "Increment healthy sibling"
        output(id="sibling-count"): {sibling}
    """)

Fail this panel raises inside the boundary. The fallback displays safe ErrorInfo and its retry button invokes the current retry capability. The sibling counter lives outside the boundary and remains usable while the failed panel is replaced.

Try it live

Increment the sibling, fail the panel, increment the sibling again, and retry the panel.

What to observe

The fallback appears, the sibling keeps its count and the retried panel starts a fresh lifetime.

Healthy local panel

0
0

Take this with you

A useful boundary contains failure without disguising what a retry can guarantee.