Back to Ratatui

Use `color_eyre` with Ratatui

src/content/docs/recipes/apps/color-eyre.md

latest2.6 KB
Original Source

:::note[Source Code]

Full source code is available at: https://github.com/ratatui/ratatui-website/tree/main/code/how-to-color_eyre/

:::

The color_eyre crate provides error report handlers for panics and errors. It displays the reports formatted and in color. To use these handlers, a Ratatui app needs to restore the terminal before displaying the errors.

Installation

First add the crate to your Cargo.toml

shell
cargo add color_eyre

Call the color_eyre::install method from your main function and update the return value to color_eyre::Result<()>.

rust
{{ #include @code/recipes/how-to-color_eyre/src/main.rs:main }}

In your terminal initialization function, add some new code that replaces rusts default panic handler with one that restores the terminal before displaying the panic details. This will be used by both panics and unhandled errors that fall through to the end of the program.

rust
{{ #include @code/recipes/how-to-color_eyre/src/tui.rs:init }}
</details>

Usage

In your application, wrap errors with extra context as needed:

Add the following import:

rust
// main.rs
{{ #include @code/recipes/how-to-color_eyre/src/main.rs:error_imports}}

Call wrap_err from methods that can fail with an error.

rust
// main.rs
{{ #include @code/recipes/how-to-color_eyre/src/main.rs:main}}

Demo

<details><summary>Full code</summary>
rust
// main.rs
{{ #include @code/recipes/how-to-color_eyre/src/main.rs }}
rust
// tui.rs
{{ #include @code/recipes/how-to-color_eyre/src/tui.rs }}
</details>

Panic

With RUST_BACKTRACE=full:

Error

With RUST_BACKTRACE=full:

Normal exit

Further Steps

See the color_eyre docs and examples for more advanced setups. E.g.: