summaryrefslogtreecommitdiff
path: root/exes/all-in-one/src/errors.rs
blob: d2c7444c9b1d419d6bce488b644e7378a0659bb4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use std::cell::RefCell;

use anyhow::Result;
use tracing::error;

thread_local! {
    pub static ERROR_HANDLER: std::cell::RefCell<Option<unsafe extern "C" fn(libc::c_int, *mut libc::c_char)>>  = RefCell::new(None);
}

/// Update the most recent error, clearing whatever may have been there before.
#[must_use] pub fn stacktrace(err: &anyhow::Error) -> String {
    format!("{err}")
}

pub fn wrap_result<T, F>(func: F) -> Option<T>
where
    F: Fn() -> Result<T>,
{
    let result = func();

    match result {
        Ok(ok) => Some(ok),
        Err(error) => {
            // Call the handler
            handle_error(&error);
            None
        }
    }
}

/// # Panics
/// Panics if the stacktrace size is > than an i32
pub fn handle_error(error: &anyhow::Error) {
    ERROR_HANDLER.with(|val| {
        let mut stacktrace = stacktrace(error);

        error!("Error emitted: {}", stacktrace);
        if let Some(func) = *val.borrow() {
            // Call the error handler
            unsafe {
                func(
                    (stacktrace.len() + 1).try_into().unwrap(),
                    stacktrace.as_mut_ptr().cast::<libc::c_char>(),
                );
            }
        }
    });
}

#[cfg(test)]
mod tests {
    // todo
}