eframe/web/
panic_handler.rs1use std::sync::Arc;
2
3use egui::mutex::Mutex;
4use wasm_bindgen::prelude::*;
5
6#[derive(Clone)]
12pub struct PanicHandler(Arc<Mutex<PanicHandlerInner>>);
13
14impl PanicHandler {
15 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 error(format!(
26 "{}\n\nStack:\n\n{}",
27 summary.message(),
28 summary.callstack()
29 ));
30
31 handler_clone.0.lock().summary = Some(summary);
33
34 previous_hook(panic_info);
36 }));
37
38 handler
39 }
40
41 pub fn has_panicked(&self) -> bool {
43 self.0.lock().summary.is_some()
44 }
45
46 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#[derive(Clone, Debug)]
62pub struct PanicSummary {
63 message: String,
64 callstack: String,
65}
66
67impl PanicSummary {
68 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 pub fn message(&self) -> String {
77 self.message.clone()
78 }
79
80 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}