Skip to main content

eframe/web/
panic_handler.rs

1use std::sync::Arc;
2
3use egui::mutex::Mutex;
4use wasm_bindgen::prelude::*;
5
6/// Detects panics, logs them using `console.error`, and stores the panics message and callstack.
7///
8/// This lets you query `PanicHandler` for the panic message (if any) so you can show it in the HTML.
9///
10/// Chep to clone (ref-counted).
11#[derive(Clone)]
12pub struct PanicHandler(Arc<Mutex<PanicHandlerInner>>);
13
14impl PanicHandler {
15    /// Install a panic hook.
16    pub fn install() -> Self {
17        let handler = Self(Arc::new(Mutex::new(Default::default())));
18
19        let handler_clone = handler.clone();
20        let previous_hook = std::panic::take_hook();
21        std::panic::set_hook(Box::new(move |panic_info| {
22            let summary = PanicSummary::new(panic_info);
23
24            // Log it using console.error
25            error(format!(
26                "{}\n\nStack:\n\n{}",
27                summary.message(),
28                summary.callstack()
29            ));
30
31            // Remember the summary:
32            handler_clone.0.lock().summary = Some(summary);
33
34            // Propagate panic info to the previously registered panic hook
35            previous_hook(panic_info);
36        }));
37
38        handler
39    }
40
41    /// Has there been a panic?
42    pub fn has_panicked(&self) -> bool {
43        self.0.lock().summary.is_some()
44    }
45
46    /// What was the panic message and callstack?
47    pub fn panic_summary(&self) -> Option<PanicSummary> {
48        self.0.lock().summary.clone()
49    }
50}
51
52#[derive(Clone, Default)]
53struct PanicHandlerInner {
54    summary: Option<PanicSummary>,
55}
56
57/// Contains a summary about a panics.
58///
59/// This is basically a human-readable version of [`std::panic::PanicHookInfo`]
60/// with an added callstack.
61#[derive(Clone, Debug)]
62pub struct PanicSummary {
63    message: String,
64    callstack: String,
65}
66
67impl PanicSummary {
68    /// Construct a summary from a panic.
69    pub fn new(info: &std::panic::PanicHookInfo<'_>) -> Self {
70        let message = info.to_string();
71        let callstack = Error::new().stack();
72        Self { message, callstack }
73    }
74
75    /// The panic message.
76    pub fn message(&self) -> String {
77        self.message.clone()
78    }
79
80    /// The backtrace.
81    pub fn callstack(&self) -> String {
82        self.callstack.clone()
83    }
84}
85
86#[wasm_bindgen]
87extern "C" {
88    #[wasm_bindgen(js_namespace = console)]
89    fn error(msg: String);
90
91    type Error;
92
93    #[wasm_bindgen(constructor)]
94    fn new() -> Error;
95
96    #[wasm_bindgen(structural, method, getter)]
97    fn stack(error: &Error) -> String;
98}