Skip to content

Commit

Permalink
Automatically convert to external errors
Browse files Browse the repository at this point in the history
A pattern documented by thiserror is

```
pub enum MyError {
  ...

  #[error(transparent)]
  Other(#[from] anyhow::Error), // source and Display delegate to anyhow::Error
}
```

It'd be nice for this to work with ensure! but right now, that macro returns
an eyre error.

With this PR, the macro additionally runs an .into(). In the case that
the return type is an eyre error, obviously .into() will do nothing and
be compiled away. In the case that there is a from method, the wrapping
will occur. This enables eyre to be used for ergonomic 'implementation
detail error' in a thiserror using system which has contractual errors.
  • Loading branch information
j-baker committed May 2, 2023
1 parent c32a8d0 commit 73c0582
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@
#[macro_export]
macro_rules! bail {
($msg:literal $(,)?) => {
return $crate::private::Err($crate::eyre!($msg));
return $crate::private::Err($crate::eyre!($msg).into());
};
($err:expr $(,)?) => {
return $crate::private::Err($crate::eyre!($err));
return $crate::private::Err($crate::eyre!($err).into());
};
($fmt:expr, $($arg:tt)*) => {
return $crate::private::Err($crate::eyre!($fmt, $($arg)*));
return $crate::private::Err($crate::eyre!($fmt, $($arg)*).into());
};
}

Expand Down Expand Up @@ -109,17 +109,17 @@ macro_rules! bail {
macro_rules! ensure {
($cond:expr, $msg:literal $(,)?) => {
if !$cond {
return $crate::private::Err($crate::eyre!($msg));
return $crate::private::Err($crate::eyre!($msg).into());
}
};
($cond:expr, $err:expr $(,)?) => {
if !$cond {
return $crate::private::Err($crate::eyre!($err));
return $crate::private::Err($crate::eyre!($err).into());
}
};
($cond:expr, $fmt:expr, $($arg:tt)*) => {
if !$cond {
return $crate::private::Err($crate::eyre!($fmt, $($arg)*));
return $crate::private::Err($crate::eyre!($fmt, $($arg)*).into());
}
};
}
Expand Down
16 changes: 16 additions & 0 deletions tests/test_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,22 @@ fn test_ensure() {
Ok(())
};
assert!(f().is_err());

let f = || -> Result<(), SomeWrappingErr> {
ensure!(false, "this will fail");
Ok(())
};
assert!(f().is_err());
}

struct SomeWrappingErr {
err: eyre::Error,
}

impl From<eyre::Error> for SomeWrappingErr {
fn from(err: eyre::Error) -> Self {
SomeWrappingErr { err }
}
}

#[test]
Expand Down

0 comments on commit 73c0582

Please sign in to comment.