eyre

repository·master·Indexed 23 days ago

https://github.com/eyre-rs/eyre

A trait object based error handling library for Rust that provides idiomatic error reporting and customization through interchangeable report handlers. It includes companion crates such as color-eyre for colorful, well-formatted error reports and panic handling, simple-eyre for minimal reporting, and color-spantrace for colorizing tracing_error::SpanTrace objects.

Tokens
10.4K
Snippets
41
Records
61
Agent score
83%

What's inside eyre

  1. Customize error reporting with Handlers

    master

    The core feature of eyre is the ability to swap the EyreHandler to change what information is carried (like backtraces) and how the report is formatted.

    Common companion crates include:

    • color-eyre: Captures backtrace::Backtrace and tracing_error::SpanTrace. Provides a Help trait for attaching warnings/suggestions and pretty-prints reports with colors.
    • stable-eyre: Uses backtrace-rs to allow backtrace capture on stable Rust.
    • simple-eyre: A minimal handler that captures no additional information (no backtraces).
    • jane-eyre: A re-export of color-eyre.
  2. When to use eyre vs thiserror

    master

    Choosing between eyre and thiserror depends on your target audience:

    • Use eyre in application code where you primarily want to report errors to a user or log, and you don't expect to programmatically match on specific error variants.
    • Use thiserror in library crates where you want to define specific, structured error types that your users can match on to handle different failure cases.
  3. Configure custom filters for color-backtrace

    master
    The pretty printing for backtraces is handled by the color-backtrace dependency. You can use the install function to set up a custom BacktracePrinter with custom filters (e.g., to hide specific frames) or customized color schemes.
  4. Use eyre for idiomatic error handling

    master

    eyre provides eyre::Report, a trait object based error handling type. It is designed for easy, idiomatic error reporting in Rust applications, particularly where you want to report errors rather than programmatically handle every specific error variant.

    Use eyre::Result<T> as the return type for fallible functions and the ? operator to propagate errors that implement std::error::Error.

    use eyre::Result;
    
    fn get_cluster_info() -> Result<ClusterMap> {
        let config = std::fs::read_to_string("cluster.json")?;
        let map: ClusterMap = serde_json::from_str(&config)?;
        Ok(map)
    }
  5. Improve color-eyre performance in debug builds

    master

    In debug mode, color-eyre can be significantly slower than eyre because it uses the backtrace crate instead of std::backtrace. To mitigate this, you can instruct Cargo to build the backtrace crate with optimizations even in dev profiles by adding this to your Cargo.toml:

    [profile.dev.package.backtrace]
    opt-level = 3
  6. Wrap errors with context using ResultExt

    master

    To improve troubleshooting, wrap lower-level errors with high-level context using the wrap_err or wrap_err_with methods from the eyre::ResultExt trait. This creates an error chain that explains the higher-level step that failed.

    • wrap_err("message"): Adds a static error message.
    • wrap_err_with(|| "message"): Adds a dynamic error message via a closure.
    use eyre::{ResultExt, Result};
    
    fn main() -> Result<()> {
        // ...
        it.detach().wrap_err("Failed to detach the important thing")?;
    
        let content = std::fs::read(path)
            .wrap_err_with(|| format!("Failed to read instrs from {}", path))?;
        // ...
        Ok(())
    }
  7. Install and setup color-eyre

    master

    To use color-eyre for colorful and well-formatted error reports and panic handling, add it to your dependencies and call color_eyre::install() at the start of your application.

    Cargo.toml

    [dependencies]
    color-eyre = "0.6"

    Rust code

    use color_eyre::eyre::Result;
    
    fn main() -> Result<()> {
        color_eyre::install()?;
    
        // ...
        Ok(())
    }
    [dependencies]
    color-eyre = "0.6"
    use color_eyre::eyre::Result;
    
    fn main() -> Result<()> {
        color_eyre::install()?;
    
        // ...
        # Ok(())
    }
  8. Enable anyhow compatibility in eyre

    master

    eyre is designed to be a drop-in replacement for anyhow. By default, the compatibility layer is disabled. To enable it, add the anyhow feature in your Cargo.toml:

    eyre = { version = "0.6", features = ["anyhow"] }
  9. Configure tracing-subscriber with ErrorLayer

    master

    To capture span traces, you must initialize a tracing_subscriber with an ErrorLayer from the tracing-error crate:

    use tracing_error::ErrorLayer;
    use tracing_subscriber::{prelude::*, registry::Registry};
    
    Registry::default().with(ErrorLayer::default()).init();