Skip to content

Commit 878c131

Browse files
committed
Make panic errors available and display them nicely for the demo
1 parent c675a59 commit 878c131

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

wasm/demo/src/main.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,18 @@ function runCodeFromTextarea() {
3636
if (result !== null) {
3737
consoleElement.value += `\n${result}\n`;
3838
}
39-
} catch (e) {
40-
errorElement.textContent = e;
41-
console.error(e);
39+
} catch (err) {
40+
if (err instanceof WebAssembly.RuntimeError) {
41+
err = window.__RUSTPYTHON_ERROR || err;
42+
}
43+
errorElement.textContent = err;
44+
console.error(err);
4245
}
4346
}
4447

4548
document
4649
.getElementById('run-btn')
4750
.addEventListener('click', runCodeFromTextarea);
4851

49-
runCodeFromTextarea(); // Run once for demo
52+
// Run once for demo
53+
runCodeFromTextarea();

wasm/lib/src/lib.rs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,34 @@ extern crate wasm_bindgen;
99
extern crate web_sys;
1010

1111
use js_sys::{Object, Reflect, TypeError};
12+
use std::panic;
1213
use wasm_bindgen::prelude::*;
1314

1415
pub use crate::vm_class::*;
1516

1617
const PY_EVAL_VM_ID: &str = "__py_eval_vm";
1718

18-
extern crate console_error_panic_hook;
19+
fn panic_hook(info: &panic::PanicInfo) {
20+
// If something errors, just ignore it; we don't want to panic in the panic hook
21+
use js_sys::WebAssembly::RuntimeError;
22+
let window = match web_sys::window() {
23+
Some(win) => win,
24+
None => return,
25+
};
26+
let msg = &info.to_string();
27+
let _ = Reflect::set(&window, &"__RUSTPYTHON_ERROR_MSG".into(), &msg.into());
28+
let error = RuntimeError::new(&msg);
29+
let _ = Reflect::set(&window, &"__RUSTPYTHON_ERROR".into(), &error);
30+
let stack = match Reflect::get(&error, &"stack".into()) {
31+
Ok(stack) => stack,
32+
Err(_) => return,
33+
};
34+
let _ = Reflect::set(&window, &"__RUSTPYTHON_ERROR_STACK".into(), &stack.into());
35+
}
1936

2037
#[wasm_bindgen(start)]
2138
pub fn setup_console_error() {
22-
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
39+
std::panic::set_hook(Box::new(panic_hook));
2340
}
2441

2542
// Hack to comment out wasm-bindgen's generated typescript definitons

0 commit comments

Comments
 (0)