Trait anyhow::Context[][src]

pub trait Context<T, E>: Sealed {
    fn context<C>(self, context: C) -> Result<T, Error>
    where
        C: Display + Send + Sync + 'static
;
fn with_context<C, F>(self, f: F) -> Result<T, Error>
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C
; }

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 {
    pub fn detach(&mut self) -> Result<()> {...}
}

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)

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, context: C) -> Result<T, Error> where
    C: Display + Send + Sync + 'static, 
[src]

Wrap the error value with additional context.

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

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

Loading content...

Implementations on Foreign Types

impl<T, E> Context<T, E> for Result<T, E> where
    E: StdError + Send + Sync + 'static, 
[src]

impl<T> Context<T, Infallible> for Option<T>[src]

use anyhow::{Context, Result};

fn maybe_get() -> Option<T> {
    ...
}

fn demo() -> Result<()> {
    let t = maybe_get().context("there is no T")?;
    ...
}
Loading content...

Implementors

Loading content...