hyperlit_base/
result.rs

1use crate::error::HyperlitError;
2
3pub type HyperlitResult<T> = Result<T, HyperlitError>;
4
5pub use tracing::info;
6
7#[macro_export]
8macro_rules! context {
9    ($fmt:expr $(, $($args:expr),+)? => $($stmts:stmt)+) => {
10        (|| {
11            $crate::result::info!($fmt $(, $($args),+)?);
12            $($stmts)+
13        })().map_err(|e| $crate::error::HyperlitError::from(e).change_context(format!(concat!("Failed to ",$fmt) $(, $($args),+)?)))
14    };
15}
16
17#[cfg(test)]
18mod tests {
19    use crate::result::HyperlitResult;
20    use crate::{bail, context};
21    use std::env::set_var;
22    use std::num::ParseFloatError;
23    use std::str::FromStr;
24
25    #[test]
26    fn test_context_macro_ok() {
27        let _result = {
28            context!("grok stuff for {}", "bar" =>
29                Ok::<i32, std::io::Error>(0)
30            )
31        }
32        .unwrap();
33    }
34
35    #[test]
36    fn test_context_macro_err() {
37        unsafe { set_var("RUST_BACKTRACE", "1") };
38        fn my_broken_function() -> HyperlitResult<u32> {
39            bail!("ungrokkable");
40        }
41        let result = {
42            context!("grok stuff for {}", "bar" => {
43                my_broken_function()
44            })
45        }
46        .expect_err("Should have errored, but was");
47        assert_eq!("Failed to grok stuff for bar", result.to_string());
48        assert!(format!("{:?}", result).contains("my_broken_function"));
49    }
50
51    #[test]
52    fn test_context_macro_err2() {
53        fn my_broken_function() -> Result<f32, ParseFloatError> {
54            f32::from_str("xyz")
55        }
56        let result = {
57            context!("grok stuff for {}", "bar" => {
58                my_broken_function()
59            })
60        }
61        .expect_err("Should have errored, but was");
62        assert_eq!("Failed to grok stuff for bar", result.to_string());
63    }
64}