Skip to content
Myr

Add Error::msg constructor to simplify map_err combinators

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 360c93a · Browse files · 2 files+45 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

2 files+45 added−0 removed

  • other:+45 added−0 removed

2 files+45 added−0 removed

modified:src/error.rs+44 added
21 unmodified lines
22 let backtrace = backtrace_if_absent!(error);23 Error::from_std(error, backtrace)24 }2526 /// Create a new error object from a printable error message.27 ///28 /// If the argument implements std::error::Error, prefer `Error::new`29 /// instead which preserves the underlying error's cause chain and30 /// backtrace. If the argument may or may not implement std::error::Error31 /// now or in the future, use `anyhow!(err)` which handles either way32 /// correctly.33 ///34 /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally35 /// convenient in places where a function is preferable over a macro, such36 /// as iterator or stream combinators:37 ///38 /// ```39 /// # mod ffi {40 /// # pub struct Input;41 /// # pub struct Output;42 /// # pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {43 /// # unimplemented!()44 /// # }45 /// # }46 /// #47 /// # use ffi::{Input, Output};48 /// #49 /// use anyhow::{Error, Result};50 /// use futures::stream::{Stream, StreamExt, TryStreamExt};51 ///52 /// async fn demo<S>(stream: S) -> Result<Vec<Output>>53 /// where54 /// S: Stream<Item = Input>,55 /// {56 /// stream57 /// .then(ffi::do_some_work) // returns Result<Output, &str>58 /// .map_err(Error::msg)59 /// .try_collect()60 /// .await61 /// }62 /// ```63 pub fn msg<M>(message: M) -> Self64 where65 M: Display + Debug + Send + Sync + 'static,66 {67 Error::from_adhoc(message, backtrace!())68 }6970 pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self71 where72 E: StdError + Send + Sync + 'static,73 {
702 unmodified lines
modified:Cargo.toml+1 added