diff --git a/src/lib.rs b/src/lib.rs index 15eaecc..b92bed8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -283,6 +283,9 @@ pub type Result = std::result::Result; /// ``` #[macro_export] macro_rules! bail { + ($msg:literal $(,)?) => { + return std::result::Result::Err($crate::anyhow!($msg)); + }; ($err:expr $(,)?) => { return std::result::Result::Err(std::convert::From::from($err)); }; diff --git a/tests/macros.rs b/tests/macros.rs new file mode 100644 index 0000000..e670ef1 --- /dev/null +++ b/tests/macros.rs @@ -0,0 +1,28 @@ +use anyhow::{bail, Result}; +use std::io; + +fn bail_literal() -> Result<()> { + bail!("oh no!"); +} + +fn bail_fmt() -> Result<()> { + bail!("{} {}!", "oh", "no"); +} + +fn bail_error() -> Result<()> { + bail!(io::Error::new(io::ErrorKind::Other, "oh no!")); +} + +#[test] +fn test_messages() { + assert_eq!("oh no!", bail_literal().unwrap_err().to_string()); + assert_eq!("oh no!", bail_fmt().unwrap_err().to_string()); + assert_eq!("oh no!", bail_error().unwrap_err().to_string()); +} + +#[test] +fn test_downcast() { + assert_eq!("oh no!", bail_literal().unwrap_err().downcast::<&str>().unwrap()); + assert_eq!("oh no!", bail_fmt().unwrap_err().downcast::().unwrap()); + assert_eq!("oh no!", bail_error().unwrap_err().downcast::().unwrap().to_string()); +}