[][src]Trait anyhow::Context

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.jsox

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

Required methods

fn context<C>(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, 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.

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, Error> for Result<T, Error>[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...