Skip to content

Commit

Permalink
Export 'Error::chain()'. Impl 'Error: From<&str>'.
Browse files Browse the repository at this point in the history
  • Loading branch information
SergioBenitez committed Apr 10, 2024
1 parent 6253b25 commit 6370f6b
Showing 1 changed file with 44 additions and 8 deletions.
52 changes: 44 additions & 8 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,17 @@ pub type Result<T> = std::result::Result<T, Error>;
///
/// Broadly, there are two ways to construct an `Error`:
///
/// * Via an error message, since `Error` impls `From<String>`:
/// * With an error message, as `Error` impls `From<String>` and `From<&str>`:
///
/// ```
/// use figment::Error;
///
/// Error::from("whoops, something went wrong!".to_string());
/// Error::from(format!("{} is invalid", 1));
///
/// Error::from("whoops, something went wrong!");
/// ```
///
/// * Via a [`Kind`], since `Error` impls `From<Kind>`:
/// * With a [`Kind`], as `Error` impls `From<Kind>`:
///
/// ```
/// use figment::{error::{Error, Kind}, value::Value};
Expand Down Expand Up @@ -144,11 +146,6 @@ impl Error {
self
}

pub(crate) fn chain(self, mut error: Error) -> Self {
error.prev = Some(Box::new(self));
error
}

pub(crate) fn retagged(mut self, tag: Tag) -> Self {
if self.tag.is_default() {
self.tag = tag;
Expand Down Expand Up @@ -201,6 +198,39 @@ impl Error {
self
}

/// Prepends `self` to `error` and returns `error`.
///
/// ```rust
/// use figment::error::Error;
///
/// let e1 = Error::from("1");
/// let e2 = Error::from("2");
/// let e3 = Error::from("3");
///
/// let error = e1.chain(e2).chain(e3);
/// assert_eq!(error.count(), 3);
///
/// let unchained = error.into_iter()
/// .map(|e| e.to_string())
/// .collect::<Vec<_>>();
/// assert_eq!(unchained, vec!["3", "2", "1"]);
///
/// let e1 = Error::from("1");
/// let e2 = Error::from("2");
/// let e3 = Error::from("3");
/// let error = e3.chain(e2).chain(e1);
/// assert_eq!(error.count(), 3);
///
/// let unchained = error.into_iter()
/// .map(|e| e.to_string())
/// .collect::<Vec<_>>();
/// assert_eq!(unchained, vec!["1", "2", "3"]);
/// ```
pub fn chain(self, mut error: Error) -> Self {
error.prev = Some(Box::new(self));
error
}

/// Returns the number of errors represented by `self`.
///
/// # Example
Expand Down Expand Up @@ -386,6 +416,12 @@ impl From<Kind> for Error {
}
}

impl From<&str> for Error {
fn from(string: &str) -> Error {
Kind::Message(string.into()).into()
}
}

impl From<String> for Error {
fn from(string: String) -> Error {
Kind::Message(string).into()
Expand Down

0 comments on commit 6370f6b

Please sign in to comment.