Skip to content
Myr

Document Context trait with example

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Tolnay · committed by David Tolnay · parent a653351 · Browse files · 1 file+43 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+43 added−1 removed

  • other:+43 added−1 removed

1 file+43 added−1 removed

modified:src/context.rs+43 added-1 removed
4 unmodified lines
5#[cfg(backtrace)]6use std::backtrace::Backtrace;78/// Provides the `context` method for `Result`.9///10/// # Example11///12/// ```13/// use anyhow::{Context, Result};14/// use std::fs;15/// use std::path::PathBuf;16///17/// pub struct ImportantThing {18/// path: PathBuf,19/// }20///21/// impl ImportantThing {22/// # const IGNORE: &'static str = stringify! {23/// pub fn detach(&mut self) -> Result<()> {...}24/// # };25/// # fn detach(&mut self) -> Result<()> {26/// # unimplemented!()27/// # }28/// }29///30/// pub fn do_it(mut it: ImportantThing) -> Result<Vec<u8>> {31/// it.detach().context("failed to detach the important thing")?;32///33/// let path = &it.path;34/// let content = fs::read(path)35/// .with_context(|| format!("failed to read instrs from {}", path.display()))?;36///37/// Ok(content)38/// }39/// ```40///41/// When printed, the outermost context would be printed first and the lower42/// level underlying causes would be enumerated below.43///44/// ```console45/// Error: failed to read instrs from ./path/to/instrs.jsox46///47/// caused by:48/// 0: No such file or directory (os error 2)49/// ```50pub trait Context<T, E> {51 /// Wrap the error value with additional context.52 fn context<C>(self, context: C) -> Result<T, Error>53 where54 C: Display + Send + Sync + 'static;5515 /// Wrap the error value with additional context lazily.56 /// Wrap the error value with additional context that is evaluated lazily57 /// only once an error does occur.58 fn with_context<C, F>(self, f: F) -> Result<T, Error>59 where60 C: Display + Send + Sync + 'static,61 F: FnOnce() -> C;
96 unmodified lines