zgui

Error handling

Show errors in the interface with Result and ErrorBoundary, handle start-up errors, avoid panics, and find failures that only appear in logs.

Errors in a zgui application surface in different places, and each kind is handled differently:

FailureTypeWhere it surfacesRecovery
A view cannot renderViewErrorthe nearest ErrorBoundaryshow a fallback for that part of the interface
The application cannot startzgui::Errorthe return value of runreport it and exit
A framework rule was brokena panicthe process unwindsfix the call; see Panics
Something fails silentlynoneonly in tracing logs, or nowheresee Troubleshooting

Show an error from a Result

A Result whose Ok value is a view is itself a view:

impl<V: View, E: Display + 'static> View for Result<V, E>

The error only needs Display + 'static. It does not have to implement std::error::Error or be Send.

use zgui::prelude::*;

#[component]
fn Reading(line: Signal<String>) -> impl IntoView {
    view! {
        row(class = "reading") {
            {move || line.with(|line| parse(line)).map(|value| view! {
                text(class = "reading__value") {{format!("{value:.2}")}}
            })}
        }
    }
}

fn parse(line: &str) -> Result<f32, String> {
    line.trim()
        .parse::<f32>()
        .map_err(|error| format!("{line:?} is not a number: {error}"))
}

The closure re-runs whenever line changes.

  • Ok(view) builds the view in place.
  • Err(error) renders nothing and sends ViewError::new(error) to the nearest ErrorBoundary above.

When a Result that was Ok becomes Err, the old content is removed first, so the last good render does not stay on screen.

With no boundary above, an Err renders nothing and the error is dropped silently. Put a boundary at the root of every application.

Catch errors with ErrorBoundary

impl<C, F> ErrorBoundary<C, F>
where
    C: Fn() -> AnyView + 'static,
    F: Fn(&[ViewError]) -> AnyView + 'static,
{
    pub fn new(children: C, fallback: F) -> Self;
}

Children first, fallback second. The fallback receives every error reported so far, oldest first. ErrorBoundary has no attribute form; write it as a value in a braced child:

use zgui::prelude::*;

#[component]
fn Panel(line: Signal<String>) -> impl IntoView {
    view! {
        column(class = "panel") {
            label(class = "panel__title") {"Latest reading"}
            {ErrorBoundary::new(
                move || AnyView::new(view! { Reading(line = line) }),
                |errors: &[ViewError]| {
                    let messages: Vec<&str> = errors.iter().map(ViewError::message).collect();
                    AnyView::new(view! {
                        box(class = "panel__failure") {
                            label {"This reading could not be shown."}
                            text(class = "panel__why") {{messages.join("\n")}}
                        }
                    })
                },
            )}
        }
    }
}

The boundary provides an error list to everything built below it, at any depth. While the list is empty, the children show. Once an error is reported, the next flush replaces the children with the fallback. Nothing wrong is visible in between, because the failing Result already rendered nothing.

A fallback must not report an error itself. It would write into the list it reads and re-run until the per-flush iteration budget stops it, which is logged at error level through tracing.

Report an error without a Result

pub struct ViewError(/* private */);        // Clone + Debug + Display

impl ViewError {
    pub fn new(message: impl Display) -> Self;
    pub fn message(&self) -> &str;
}

pub fn report_error(error: ViewError);

A ViewError holds only a message. ViewError and ErrorBoundary are in the prelude; report_error is at zgui::view::report_error.

Call report_error when you handle a Result yourself instead of returning it as a view:

use zgui::view::report_error;

#[component]
fn Panel(source: Signal<String>) -> impl IntoView {
    if let Err(error) = check(&source.get_untracked()) {
        report_error(ViewError::new(error));
    }
    view! { column(class = "panel") { /* … */ } }
}

report_error finds the boundary through the current owner (see Context), not through the element tree:

Called fromReaches the boundary
a component bodyyes
a reactive hole or effect below the boundaryyes
an on: listener below the boundaryyes: listeners run in the scope they were written in
a spawned taskno: no owner is current while a task is polled

Report a failure from a task

Because a task has no owner, store its result in a signal and let a Result in the view report the error:

#[component]
fn RowCount() -> impl IntoView {
    let loaded = RwSignal::new(None::<Result<usize, String>>);

    spawn(async move {
        let result = background(async { count_rows().await }).await;
        loaded.set(Some(result.map_err(|error| error.to_string())));
    });

    view! {
        {move || loaded.get().map(|result| result.map(|count| view! {
            label {{format!("{count} rows")}}
        }))}
    }
}

None renders nothing while the task runs; Some(Err(_)) reaches the nearest boundary.

Retry after a failure

A boundary latches: once the fallback shows, it stays for as long as that boundary exists. Rebuilding the same boundary in place keeps its error list. To retry, replace the boundary with a new one. A keyed list does this when the key changes:

let attempt = RwSignal::new(0_u32);

view! {
    column(class = "panel") {
        // A new key builds a new boundary with an empty error list.
        for id in move || [attempt.get()], key = |id: &u32| *id {
            {ErrorBoundary::new(
                move || AnyView::new(view! { Reading(line = line) }),
                move |errors: &[ViewError]| AnyView::new(view! {
                    column(class = "failure") {
                        label {{format!("Attempt {id} failed.")}}
                        text {{errors[0].message().to_owned()}}
                    }
                }),
            )}
        }
        control(class = "retry", on:click = move |_| attempt.update(|n| *n += 1)) {"Try again"}
    }
}

Nest boundaries

The nearest boundary above a failure catches it. Outer boundaries never see it.

view! {
    // The backstop: catches whatever the panels do not.
    {ErrorBoundary::new(
        || AnyView::new(view! {
            column(class = "app") {
                // Each panel fails on its own; the rest of the window keeps working.
                {ErrorBoundary::new(left, panel_failure)}
                {ErrorBoundary::new(right, panel_failure)}
            }
        }),
        app_failure,
    )}
}

Put a boundary around each part of the interface that can fail independently, and one at the root. With only a root boundary, any failure replaces the whole window.

What a boundary does not catch

Not caughtDo instead
A panicPanics are not errors. See Panics.
A Result you handled yourselfCall report_error.
A failure in a spawned taskWrite it into a signal and report from the view. See Report a failure from a task.
A failure below a nearer boundaryThe nearer boundary catches it. See Nest boundaries.
The application failing to startHandle zgui::Error from run. See Handle start-up errors.

Handle start-up errors

run returns a zgui::Error when the application cannot start. Return it from main, or match on it:

fn main() -> Result<(), zgui::Error> {
    app()
        .with_title("Counter")
        .with_size(360.0, 300.0)
        .with_stylesheet(SHEET)
        .run(|| view! { Counter() })
}

If the first window fails to open, the error is logged under the tracing target zgui::app, the event loop exits, and run returns the error. If a later window fails to open, the error is logged, that window's handle is marked closed, and the other windows keep running.

No graphics adapter

Error::GpuUnavailable lists every adapter that was tried and why each was rejected. There is no fallback renderer: a window that opens and never paints looks like a hang.

fn main() -> Result<(), zgui::Error> {
    let outcome = app().with_title("Counter").run(|| view! { Counter() });

    if let Err(zgui::Error::GpuUnavailable(ref failure)) = outcome {
        for adapter in &failure.candidates {
            eprintln!("rejected {}: {}", adapter.name, adapter.reason);
        }
    }
    outcome
}

No display server

The result is Error::Platform(PlatformError::Backend(_)) with the windowing system's message, typically on an SSH session with no forwarded display. On Linux and the BSDs, zgui uses the native Wayland backend when a Wayland display is available and winit otherwise. ZGUI_PLATFORM=wayland or ZGUI_PLATFORM=winit forces one. If the chosen backend cannot connect, run returns the error; zgui does not silently switch to the other backend.

Stylesheet errors

WhenWhat happens
A css! sheet does not parseCompile error at the call site.
A sheet parses but a declaration is not understoodThe rest of the sheet applies; the declaration is dropped with a tracing warning under zgui::css.
A caller asks for a sheet to be fatalError::Stylesheet.
Partial· Nothing in the built-in start-up path creates Error::Stylesheet today. A bad declaration in an application sheet is a warning, not a start-up failure.

zgui::Error variants

zgui::Error is zgui_runtime::AppError. It is #[non_exhaustive], so a match needs a _ arm.

VariantCauseMessage
Platform(PlatformError)The desktop refused something the application needs.the platform could not satisfy the application: …
GpuUnavailable(GpuUnavailable)No graphics adapter could be used.no usable graphics device: N adapter(s) were tried and rejected
ForeignExecutorAnother async runtime already holds this process's executor slot.another async executor is already installed in this process
Stylesheet(String)A stylesheet a caller asked to treat as fatal was rejected.the application stylesheet was rejected: …
DocumentsExhaustedThe process has opened every window it can name (document identities are never reused).this process has opened every window it can name

PlatformError is also #[non_exhaustive]:

VariantMessage
Unsupported(Unsupported)the platform does not support this request
SurfaceCreation(String)the surface could not be created: …
NoSuchSurfacethat surface no longer exists
Backend(String)the backend's own message

Panics

zgui catches no panics. An ErrorBoundary does not catch them, and a panic in a UI task reaches the frame loop. These are the panics your code can trigger:

CallConditionBuilds
expect_context::<T>()No scope above provides a T.all
reading or writing a signalIts owner was disposed of.all
Callable::runThe callback's owner was disposed of.all
reading a LocalStorage signal, or dropping a local valueOn a different thread from the one that created it.all
use_local_context::<T>()The value was provided on a different thread.all
awaiting a background or blocking resultThe work panicked, or the executor shut down before it finished.all
provide_context, provide_local_context, on_cleanup_local, Selector::is_selectedNo current owner.debug
flush, spawn, spawn_local, spawn_detached, ui, Mounted::new, Scope::mount, provide_local_context, use_local_contextOff the UI thread.debug
set_timeout, set_interval, request_frameOutside a window's scope.debug
install_stylesheet, remove_stylesheetOutside a window's scope.debug

The debug-only checks compile away in release, where the call silently does nothing (or leaks). Run your interface in a debug build at least once.

Avoid common panics

PanicFix
Missing contextUse use_context and handle None, or provide the value higher up.
Disposed signal or callbackDon't keep a handle past its scope. Where a closure may outlive it, use try_get, try_update or try_run.
Cross-thread local valueKeep view-layer values on the UI thread. Send plain data back and write the signal there.
No current ownerCreate state in a component body, not in a static, a global or a plain thread.
Off the UI threadzgui::reactive::is_ui_thread() tells you where you are.
Timer outside a window's scopeFrom a task or a posted closure, take Timers::current() in the component body and carry it in.

Panic messages

provide_context requires a current owner: with none, the value it creates is
unreachable and never freed. Run it inside `Mounted::with`.

flush must run on the thread that installed the reactive runtime

Dereferenced SendWrapper<T> variable from a thread different to the one it has
been created with.

At src/main.rs:41:18, you tried to access a reactive value which was defined at
src/main.rs:12:21, but it has already been disposed.

Troubleshooting

Many failures are only visible through tracing. Install a subscriber before the application runs, and check that reactive effects are enabled:

fn main() -> Result<(), zgui::Error> {
    tracing_subscriber::fmt().init();
    assert!(zgui::reactive::effects_are_enabled());

    app().with_title("Counter").run(|| view! { Counter() })
}

zgui logs under the targets zgui::app, zgui::css, zgui::style, zgui::layout, zgui::input, zgui::observe, zgui::paint, zgui::images and zgui::platform.

Silent failures

SymptomCauseHow to see it
The interface renders once and never changes.A signal was read outside a closure.Nothing reports it. Put changing values behind a closure.
Nothing works, in release only.State was created with no current owner and leaked.A debug build panics on that line.
Everything builds, nothing updates.Reactive effects were compiled out by a feature elsewhere in the dependency graph.assert!(zgui::reactive::effects_are_enabled()); at start-up.
Part of the interface is blank.A Result failed with no boundary above it.Add a boundary.
One CSS declaration does nothing.The engine did not understand it.A tracing warning under zgui::css.
An effect stops running.Its RenderEffect handle was dropped.#[must_use] warns. Store the handle.
Occasional late frames; a task never settles.Two reactive tasks write each other's sources; the iteration budget cuts the cycle.One tracing error per flush, naming the spawn site.
A timer never fires, in release only.set_timeout ran outside a window's scope.A debug build panics.

Fix an interface that does not update

Check, in order:

  1. Is the value behind a closure? {count.get().to_string()} is read once. {move || count.get().to_string()} re-runs when count changes. This is the usual cause.
  2. Does the closure read the signal, or a copy? A let outside the closure is a snapshot.
  3. Are effects enabled? If zgui::reactive::effects_are_enabled() is false, every view renders once and ignores all writes.
  4. Was the state created in a component body? State created with no owner never works, and only debug builds say so.
  5. Is a boundary showing its fallback? Boundaries latch, so an early failure leaves the fallback up.
  6. Is tracing on? Cycle reports, dropped declarations and windows that failed to open are only logged.
  7. Is a worker thread writing UI state? Take a Ui handle with ui() on the UI thread and call Ui::post from the worker. See Background work.
  8. Do two rows share a key? Duplicate keys make rows collapse into one another.

Next

On this page