### Anyhow Option Context Example Source: https://github.com/eyre-rs/eyre/blob/master/README.md This example demonstrates how `anyhow` handles context for `Option` types using the `context` method. ```rust use anyhow::Context; let opt: Option<()> = None; let result_static = opt.context("static error message"); let result_dynamic = opt.with_context(|| format!("{}" error message", "dynamic")); ``` -------------------------------- ### Install and Use simple-eyre Handler Source: https://github.com/eyre-rs/eyre/blob/master/simple-eyre/README.md Install the simple-eyre handler before creating eyre::Report types. This example demonstrates creating a basic error and wrapping it. ```rust use simple_eyre::eyre::{eyre, ResultExt, Report}; fn main() -> Result<(), Report> { simple_eyre::install()?; let e: Report = eyre!("oh no this program is just bad!"); Err(e).wrap_err("usage example successfully experienced a failure") } ``` -------------------------------- ### Full Usage Example Source: https://github.com/eyre-rs/eyre/blob/master/color-spantrace/README.md Demonstrates setting up tracing, capturing spans across multiple functions, and colorizing the final SpanTrace. ```rust use tracing::instrument; use tracing_error::{ErrorLayer, SpanTrace}; use tracing_subscriber::{prelude::*, registry::Registry}; #[instrument] fn main() { Registry::default().with(ErrorLayer::default()).init(); let span_trace = one(42); println!("{}", color_spantrace::colorize(&span_trace)); } #[instrument] fn one(i: u32) -> SpanTrace { two() } #[instrument] fn two() -> SpanTrace { SpanTrace::capture() } ``` -------------------------------- ### Setup Tracing Subscriber with ErrorLayer Source: https://github.com/eyre-rs/eyre/blob/master/color-spantrace/README.md Initialize a tracing subscriber with the ErrorLayer to enable error reporting. ```rust use tracing_error::ErrorLayer; use tracing_subscriber::{prelude::*, registry::Registry}; Registry::default().with(ErrorLayer::default()).init(); ``` -------------------------------- ### Install color-eyre Panic and Error Handlers Source: https://github.com/eyre-rs/eyre/blob/master/color-eyre/README.md Installs the necessary handlers for color-eyre to format panics and errors. This should be called early in your application's entry point. ```rust use color_eyre::eyre::Result; fn main() -> Result<()> { color_eyre::install()?; // ... # Ok(()) } ``` -------------------------------- ### Eyre Option Handling Example Source: https://github.com/eyre-rs/eyre/blob/master/README.md This example shows how Eyre handles `Option` types using `ok_or_eyre` for static errors and `ok_or_else` for dynamic errors, aligning with Eyre's design principles. ```rust use eyre::{eyre, OptionExt, Result}; let opt: Option<()> = None; let result_static: Result<()> = opt.ok_or_eyre("static error message"); let result_dynamic: Result<()> = opt.ok_or_else(|| eyre!("{}" error message", "dynamic")); ``` -------------------------------- ### Capture Span Trace with Theming Source: https://github.com/eyre-rs/eyre/blob/master/color-spantrace/tests/data/theme_control.txt Illustrates capturing a span trace within a test function that utilizes theming. This example requires the `tracing` crate and its `instrument` macro. ```rust use tracing_subscriber::{prelude::*, registry::Registry}; #[instrument] fn test_capture(x: u8) -> SpanTrace { #[allow(clippy::if_same_then_else)] if x == 42 { SpanTrace::capture() } else { SpanTrace::capture() } } ``` -------------------------------- ### Implement Custom Sections for Error Reports Source: https://github.com/eyre-rs/eyre/blob/master/color-eyre/README.md This example demonstrates how to add custom sections like stdout and stderr to error reports using the `SectionExt` trait. It's useful for capturing command output when errors occur. ```rust use color_eyre::{eyre::eyre, SectionExt, Section, eyre::Report}; use std::process::Command; use tracing::instrument; trait Output { fn output2(&mut self) -> Result; } impl Output for Command { #[instrument] fn output2(&mut self) -> Result { let output = self.output()?; let stdout = String::from_utf8_lossy(&output.stdout); if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); Err(eyre!("cmd exited with non-zero status code")) .with_section(move || stdout.trim().to_string().header("Stdout:")) .with_section(move || stderr.trim().to_string().header("Stderr:")) } else { Ok(stdout.into()) } } } ``` -------------------------------- ### Anyhow Option Context Usage Source: https://github.com/eyre-rs/eyre/blob/master/eyre/README.md Demonstrates how to use the `context` method on Option with Anyhow for static and dynamic error messages. ```rust use anyhow::Context; let opt: Option<()> = None; let result_static = opt.context("static error message"); let result_dynamic = opt.with_context(|| format!("{} error message", "dynamic")); ``` -------------------------------- ### Enable Anyhow Compatibility in Cargo.toml Source: https://github.com/eyre-rs/eyre/blob/master/eyre/README.md To enable the Anyhow compatibility layer, add the "anyhow" feature to your Eyre dependency in Cargo.toml. ```toml eyre = { version = "0.6", features = ["anyhow"] } ``` -------------------------------- ### Add color-spantrace to Cargo.toml Source: https://github.com/eyre-rs/eyre/blob/master/color-spantrace/README.md Add the color-spantrace crate and its dependencies to your project's Cargo.toml file. ```toml [dependencies] color-spantrace = "0.2" tracing = "0.1" tracing-error = "0.2" tracing-subscriber = "0.3" ``` -------------------------------- ### Eyre Option Context Usage Source: https://github.com/eyre-rs/eyre/blob/master/eyre/README.md Shows the equivalent usage with Eyre, utilizing `ok_or_eyre` for static errors and `ok_or_else` with `eyre!` for dynamic errors. ```rust use eyre::{eyre, OptionExt, Result}; let opt: Option<()> = None; let result_static: Result<()> = opt.ok_or_eyre("static error message"); let result_dynamic: Result<()> = opt.ok_or_else(|| eyre!("{} error message", "dynamic")); ``` -------------------------------- ### Early Return with `bail!` Macro Source: https://github.com/eyre-rs/eyre/blob/master/eyre/README.md The `bail!` macro provides a shorthand for early returns with an `eyre::Report`, supporting format argument captures. ```rust bail!("Missing attribute: {}", missing); ``` ```rust bail!("Missing attribute: {missing}"); ``` -------------------------------- ### Improve Debug Build Performance Source: https://github.com/eyre-rs/eyre/blob/master/color-eyre/README.md Optimize the performance of the 'backtrace' crate in debug builds by setting its optimization level to 3 in Cargo.toml. This mitigates performance degradation compared to the 'eyre' crate. ```toml [profile.dev.package.backtrace] opt-level = 3 ``` -------------------------------- ### Colorize SpanTrace Source: https://github.com/eyre-rs/eyre/blob/master/color-spantrace/README.md Capture a SpanTrace and print its colorized representation. ```rust use tracing_error::SpanTrace; let span_trace = SpanTrace::capture(); println!("{}", color_spantrace::colorize(&span_trace)); ``` -------------------------------- ### Create and Capture Spans Source: https://github.com/eyre-rs/eyre/blob/master/color-spantrace/README.md Define instrumented functions that capture SpanTrace objects. ```rust use tracing::instrument; use tracing_error::SpanTrace; #[instrument] fn foo() -> SpanTrace { SpanTrace::capture() } ``` -------------------------------- ### Panic Output with Theme Control Source: https://github.com/eyre-rs/eyre/blob/master/color-eyre/tests/data/theme_panic_control_no_spantrace.txt This output shows a typical panic message when color-eyre is configured with theme control. It displays the panic message, location, and a filtered backtrace. Run with COLORBT_SHOW_HIDDEN=1 to see hidden frames or RUST_BACKTRACE=full for source snippets. ```text Compiling color-eyre v0.6.5 (/home/username/src/eyre/color-eyre)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s\n Running /home/username/src/eyre/target/debug/examples/theme_test_helper\nThe application panicked (crashed).\nMessage: \nLocation: color-eyre/examples/theme_test_helper.rs:38:5\n\n ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ BACKTRACE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n  ⋮ 7 frames hidden ⋮ \n 8: std::panic::panic_any::he59a839a6a44e696\n at /home/username/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/panic.rs:260:5\n 9: theme_test_helper::main::hc5e7f338a9ea403d\n at /home/username/src/eyre/color-eyre/examples/theme_test_helper.rs:38:5\n 10: core::ops::function::FnOnce::call_once::h70f9f848fb0cbb67\n at /home/username/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250:5\n  ⋮ 16 frames hidden ⋮ \n\nRun with COLORBT_SHOW_HIDDEN=1 environment variable to disable frame filtering.\nRun with RUST_BACKTRACE=full to include source snippets.\n ``` -------------------------------- ### Creating One-Off Error Messages with `eyre!` Source: https://github.com/eyre-rs/eyre/blob/master/eyre/README.md Use the `eyre!` macro to construct `eyre::Report` instances with string interpolation for one-off error messages. ```rust return Err(eyre!("Missing attribute: {}", missing)); ``` ```rust return Err(eyre!("Missing attribute: {missing}")); ``` -------------------------------- ### Wrapping Errors with Context Source: https://github.com/eyre-rs/eyre/blob/master/eyre/README.md Wrap lower-level errors with new messages using `wrap_err` or `wrap_err_with` to provide more context for debugging. This is useful for understanding the chain of failures. ```rust 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))?; ... } ``` ```console Error: Failed to read instrs from ./path/to/instrs.json Caused by: No such file or directory (os error 2) ``` -------------------------------- ### Disable color-eyre Tracing Support Source: https://github.com/eyre-rs/eyre/blob/master/color-eyre/README.md Configure color-eyre to exclude tracing integration by modifying the Cargo.toml file. This reduces dependencies if tracing is not used. ```toml [dependencies] color-eyre = { version = "0.6", default-features = false } ``` -------------------------------- ### Propagating Errors with `?` Operator Source: https://github.com/eyre-rs/eyre/blob/master/eyre/README.md Use `eyre::Result` as a return type for fallible functions and the `?` operator to propagate errors that implement `std::error::Error`. ```rust use eyre::Result; fn get_cluster_info() -> Result { let config = std::fs::read_to_string("cluster.json")?; let map: ClusterMap = serde_json::from_str(&config)?; Ok(map) } ``` -------------------------------- ### Disable SpanTrace Capture by Default Source: https://github.com/eyre-rs/eyre/blob/master/color-eyre/README.md Prevent SpanTrace capture by default by setting the RUST_SPANTRACE environment variable to "0". This can reduce noise during debugging. ```rust if std::env::var("RUST_SPANTRACE").is_err() { std::env::set_var("RUST_SPANTRACE", "0"); } ``` -------------------------------- ### Custom Error Type with `thiserror` Source: https://github.com/eyre-rs/eyre/blob/master/eyre/README.md Define custom error types using `thiserror` for use with Eyre. This allows for structured error reporting and matching. ```rust use thiserror::Error; #[derive(Error, Debug)] pub enum FormatError { #[error("Invalid header (expected {expected:?}, got {found:?})")] InvalidHeader { expected: String, found: String, }, #[error("Missing attribute: {0}")] MissingAttribute(String), } ``` -------------------------------- ### Downcasting Errors Source: https://github.com/eyre-rs/eyre/blob/master/eyre/README.md Downcasting is supported for error types, allowing you to inspect the root cause of an error by value, shared reference, or mutable reference. ```rust // If the error was caused by redaction, then return a // tombstone instead of the content. match root_cause.downcast_ref::() { Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)), None => Err(error), } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.