Trait Context

trait Context<T, E>: context::private::Sealed

Provides the context method for Result.

This trait is sealed and cannot be implemented for types outside of anyhow.


Example

use anyhow::{Context, Result};
use std::fs;
use std::path::PathBuf;

pub struct ImportantThing {
    path: PathBuf,
}

impl ImportantThing {
    # const IGNORE: &'static str = stringify! {
    pub fn detach(&mut self) -> Result<()> {...}
    # };
    # fn detach(&mut self) -> Result<()> {
    #     unimplemented!()
    # }
}

pub fn do_it(mut it: ImportantThing) -> Result<Vec<u8>> {
    it.detach().context("Failed to detach the important thing")?;

    let path = &it.path;
    let content = fs::read(path)
        .with_context(|| format!("Failed to read instrs from {}", path.display()))?;

    Ok(content)
}

When printed, the outermost context would be printed first and the lower level underlying causes would be enumerated below.

Error: Failed to read instrs from ./path/to/instrs.json

Caused by:
    No such file or directory (os error 2)

Refer to the Display representations documentation for other forms in which this context chain can be rendered.


Effect on downcasting

After attaching context of type C onto an error of type E, the resulting anyhow::Error may be downcast to C or to E.

That is, in codebases that rely on downcasting, Anyhow's context supports both of the following use cases:

Required Methods

fn context<C>(self: Self, context: C) -> Result<T, Error>
where
    C: Display + Send + Sync + 'static

Wrap the error value with additional context.

fn with_context<C, F>(self: Self, f: F) -> Result<T, Error>
where
    C: Display + Send + Sync + 'static,
    F: FnOnce() -> C

Wrap the error value with additional context that is evaluated lazily only once an error does occur.

Implementors