Skip to main content

ErrorContext

Trait ErrorContext 

Source
pub trait ErrorContext<T> {
    // Required methods
    fn context(self, context: impl Into<String>) -> Result<T>;
    fn with_context<F, C>(self, f: F) -> Result<T>
       where F: FnOnce() -> C,
             C: Into<String>;
}
Expand description

Extension trait for adding context to errors.

This trait provides methods to add context information to errors, creating a chain of context that helps trace the source of problems.

§Example

use sbom_tools::error::ErrorContext;

fn parse_component(data: &str) -> Result<Component> {
    let json: Value = serde_json::from_str(data)
        .context("parsing component JSON")?;

    extract_component(&json)
        .with_context(|| format!("extracting component from {}", data.chars().take(50).collect::<String>()))?
}

fn load_sbom(path: &Path) -> Result<NormalizedSbom> {
    let content = std::fs::read_to_string(path)
        .context("reading SBOM file")?;

    parse_sbom_str(&content)
        .with_context(|| format!("parsing SBOM from {}", path.display()))?
}

Required Methods§

Source

fn context(self, context: impl Into<String>) -> Result<T>

Add context to an error.

The context string is prepended to the error’s existing context, creating a chain that shows the path through the code.

Source

fn with_context<F, C>(self, f: F) -> Result<T>
where F: FnOnce() -> C, C: Into<String>,

Add context from a closure (lazy evaluation).

The closure is only called if the result is an error, which is more efficient when the context string is expensive to compute.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T, E: Into<SbomDiffError>> ErrorContext<T> for Result<T, E>

Source§

fn context(self, context: impl Into<String>) -> Result<T>

Source§

fn with_context<F, C>(self, f: F) -> Result<T>
where F: FnOnce() -> C, C: Into<String>,

Implementors§