1use std::any::Any;
5use std::panic::{AssertUnwindSafe, catch_unwind};
6
7pub fn catch<R>(work: impl FnOnce() -> R) -> Result<R, String> {
17 catch_unwind(AssertUnwindSafe(work)).map_err(|payload| message(&*payload))
18}
19
20#[must_use]
22pub(crate) fn message(payload: &(dyn Any + Send)) -> String {
23 if let Some(message) = payload.downcast_ref::<&str>() {
24 (*message).to_owned()
25 } else if let Some(message) = payload.downcast_ref::<String>() {
26 message.clone()
27 } else {
28 "a panic without a message".to_owned()
29 }
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35
36 #[test]
37 fn returns_the_result_of_work_that_returns() {
38 assert_eq!(catch(|| 7), Ok(7));
39 }
40
41 #[test]
42 fn returns_the_message_of_a_panic() {
43 assert_eq!(catch(|| panic!("static")), Err::<(), _>("static".to_owned()));
44 let value = 7;
45 assert_eq!(catch(|| panic!("formatted {value}")), Err::<(), _>("formatted 7".to_owned()));
46 assert_eq!(catch(|| std::panic::panic_any(7)), Err::<(), _>("a panic without a message".to_owned()));
47 }
48}