blob: d676e8d3837852dca7951f2f57b86fe12c3eda39 (
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
|
use std::cell::RefCell;
use anyhow::Result;
use libc::c_int;
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.
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
}
}
}
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() as c_int + 1,
stacktrace.as_mut_ptr() as *mut i8,
);
}
}
});
}
#[cfg(test)]
mod tests {
// todo
}
|