Skip to content

Commit 33836a3

Browse files
committed
melib/error: add WrapResultIntoError helper trait
Add a new WrapResultIntoError trait with method wrap_err() so we can wrap a result and set its error as a source for a new error and description, this allows for more descriptive error messages like: Before: let mbox_format = parse(some_string)?; <- error msg is "invalid mbox format value, expected blah blah" After: let mbox_format = parse(some_string).wrap_err(|| "Could parse configuration of account {}", account_name)?; <- error msg is "Could not parse configuration of account myaccount, Caused by: invalid mbox format value, expected blah blah" Signed-off-by: Manos Pitsidianakis <[email protected]>
1 parent 374ea8b commit 33836a3

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

melib/src/error.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,18 @@ pub trait ResultIntoError<T> {
448448
fn chain_err_kind(self, kind: ErrorKind) -> Result<T>;
449449
}
450450

451+
pub trait WrapResultIntoError<T, I>
452+
where
453+
I: Send + Sync + std::error::Error + 'static,
454+
{
455+
/// Wrap a result into a new [`Error`] that sets its source to the original
456+
/// value.
457+
fn wrap_err<M, F>(self, msg_fn: F) -> Result<T>
458+
where
459+
F: Fn() -> M,
460+
M: Into<Cow<'static, str>>;
461+
}
462+
451463
impl<I: Into<Error>> IntoError for I {
452464
#[inline]
453465
fn set_err_summary<M>(self, msg: M) -> Error
@@ -499,6 +511,22 @@ impl<T, I: Into<Error>> ResultIntoError<T> for std::result::Result<T, I> {
499511
}
500512
}
501513

514+
impl<T, I> WrapResultIntoError<T, I> for std::result::Result<T, I>
515+
where
516+
I: Send + Sync + std::error::Error + 'static,
517+
{
518+
#[inline]
519+
/// Wrap a result into a new [`Error`] that sets its source to the original
520+
/// value.
521+
fn wrap_err<M, F>(self, msg_fn: F) -> Result<T>
522+
where
523+
F: Fn() -> M,
524+
M: Into<Cow<'static, str>>,
525+
{
526+
self.map_err(|err| Error::new(msg_fn()).set_source(Some(Arc::new(err))))
527+
}
528+
}
529+
502530
impl Error {
503531
pub fn new<M>(msg: M) -> Self
504532
where

0 commit comments

Comments
 (0)