Skip to content
Myr

Explain the purpose of Error::context

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 1ea72bb · Browse files · 1 file+48 added−0 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+48 added−0 removed

  • other:+48 added−0 removed

1 file+48 added−0 removed

modified:src/error.rs+48 added
77 unmodified lines
78 ///79 /// For attaching context to a `Result` as it is propagated, the80 /// [`Context`][crate::Context] extension trait may be more convenient than81 /// this function.82 ///83 /// The primary reason to use `error.context(...)` instead of84 /// `result.context(...)` via the `Context` trait would be if the context85 /// needs to depend on some data held by the underlying error:86 ///87 /// ```88 /// # use std::fmt::{self, Debug, Display};89 /// #90 /// # type T = ();91 /// #92 /// # impl std::error::Error for ParseError {}93 /// # impl Debug for ParseError {94 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {95 /// # unimplemented!()96 /// # }97 /// # }98 /// # impl Display for ParseError {99 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {100 /// # unimplemented!()101 /// # }102 /// # }103 /// #104 /// use std::fs::File;105 /// use std::path::Path;106 ///107 /// struct ParseError {108 /// line: usize,109 /// column: usize,110 /// }111 ///112 /// fn parse_impl(file: File) -> Result<T, ParseError> {113 /// # const IGNORE: &str = stringify! {114 /// ...115 /// # };116 /// # unimplemented!()117 /// }118 ///119 /// pub fn parse(path: impl AsRef<Path>) -> anyhow::Result<T> {120 /// let file = File::open(&path)?;121 /// parse_impl(file).map_err(|error| {122 /// let context = format!(123 /// "only the first {} lines of {} are valid",124 /// error.line, path.as_ref().display(),125 /// );126 /// anyhow::Error::new(error).context(context)127 /// })128 /// }129 /// ```130 pub fn context<C>(self, context: C) -> Self131 where132 C: Display + Send + Sync + 'static,133 {
341 unmodified lines