flutter_rust_bridge/handler/
error.rs1use std::any::Any;
2use std::backtrace::Backtrace;
3
4pub enum Error {
6 CustomError,
8 Panic(Box<dyn Any + Send>),
10}
11
12impl Error {
13 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}