flutter_rust_bridge/handler/
error.rs

1use std::any::Any;
2use std::backtrace::Backtrace;
3
4/// Errors that occur from normal code execution.
5pub enum Error {
6    /// Non-panic errors
7    CustomError,
8    /// Exceptional errors from panicking.
9    Panic(Box<dyn Any + Send>),
10}
11
12impl Error {
13    /// The message of the error.
14    pub fn message(&self) -> String {
15        match self {
16            Error::CustomError => "CustomError".to_string(),
17            Error::Panic(panic_err) => error_to_string(panic_err, &None),
18        }
19    }
20}
21
22pub(crate) fn error_to_string(
23    panic_err: &Box<dyn Any + Send>,
24    backtrace: &Option<Backtrace>,
25) -> String {
26    let err_string = match panic_err.downcast_ref::<&'static str>() {
27        Some(s) => *s,
28        None => match panic_err.downcast_ref::<String>() {
29            Some(s) => &s[..],
30            None => "Box<dyn Any>",
31        },
32    }
33    .to_string();
34    let backtrace_string = backtrace
35        .as_ref()
36        .map(|b| format!("{:?}", b))
37        .unwrap_or_default();
38    err_string + &backtrace_string
39}
40
41#[cfg(test)]
42mod tests {
43    use crate::handler::error::Error;
44
45    #[test]
46    fn test_error_message() {
47        assert_eq!(Error::CustomError.message(), "CustomError".to_owned());
48        assert_eq!(
49            Error::Panic(Box::new(42)).message(),
50            "Box<dyn Any>".to_owned()
51        );
52        assert_eq!(
53            Error::Panic(Box::new("Hello".to_string())).message(),
54            "Hello".to_owned()
55        );
56    }
57}