Accept string literal in bail macro

This commit is contained in:
David Tolnay 2019-10-07 12:59:14 -07:00
parent 6fa503dff5
commit 08b3d5d42b
2 changed files with 31 additions and 0 deletions

View File

@ -283,6 +283,9 @@ pub type Result<T> = std::result::Result<T, Error>;
/// ```
#[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));
};

28
tests/macros.rs Normal file
View File

@ -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::<String>().unwrap());
assert_eq!("oh no!", bail_error().unwrap_err().downcast::<io::Error>().unwrap().to_string());
}