Skip to main content

memlink_msdk/
panic.rs

1//! Panic isolation utilities for memlink modules, catching panics and converting them to errors.
2
3use std::panic::{catch_unwind, UnwindSafe};
4use std::string::ToString;
5
6use crate::error::{ModuleError, Result};
7
8pub fn catch_module_panic<F, R>(f: F) -> Result<R>
9where
10    F: FnOnce() -> R + UnwindSafe,
11{
12    match catch_unwind(f) {
13        Ok(value) => Ok(value),
14        Err(payload) => {
15            let panic_msg = if let Some(s) = payload.downcast_ref::<&str>() {
16                s.to_string()
17            } else if let Some(s) = payload.downcast_ref::<String>() {
18                s.clone()
19            } else {
20                "unknown panic".to_string()
21            };
22            Err(ModuleError::Panic(panic_msg))
23        }
24    }
25}