atagen

macltok

public
Star0
Watch0
7ef213f192883084fc424e8c97b269dd0b79d399
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/wasm.rsRust29 lines1.1 KB
1
use std::cell::RefCell;
2
3
type Handler = Box<dyn Fn(&str)>;
4
5
thread_local! {
6
    static HANDLER: RefCell<Option<Handler>> = const { RefCell::new(None) };
7
}
8
9
/// a panic on wasm32 traps the task that raised it and nothing unwinds, so the engine
10
/// catches nothing. the rest of it keeps running in an undefined state and goes silent,
11
/// no `Failed` and no `Stopped`. `handler` runs from the panic hook with the message,
12
/// after whatever hook was there before, and is the host's one chance to react, say by
13
/// terminating the worker and starting a fresh one. a second call replaces the handler
14
pub fn on_panic(handler: impl Fn(&str) + 'static) {
15
    let installed = HANDLER.with(|slot| slot.replace(Some(Box::new(handler))).is_some());
16
    if installed {
17
        return;
18
    }
19
    let previous = std::panic::take_hook();
20
    std::panic::set_hook(Box::new(move |info| {
21
        previous(info);
22
        let message = info.to_string();
23
        HANDLER.with(|slot| {
24
            if let Some(handler) = &*slot.borrow() {
25
                handler(&message);
26
            }
27
        });
28
    }));
29
}