rspack_browser/panic.rs
1//! See [install_panic_handler]
2
3/// Install panic handler for browser environment
4///
5/// Rust builtin panic handler or other community implementation always lock backtrace and stderr before printing error messages.
6/// However, requesting locks finally calls `atomics.wait`, and it's forbidden to do it in the main thread of browser.
7/// So this function provides a panic handler which directly writes error messages to stderr without locks.
8pub fn install_panic_handler() {
9 use std::{fs::File, io::Write, os::fd::FromRawFd};
10
11 std::panic::set_hook(Box::new(|info| {
12 let msg = info.to_string();
13 // SAFETY: only use this in browser, where fd 2 always points to `console.err`
14 let mut file = unsafe { File::from_raw_fd(2) };
15 file
16 .write_all(msg.as_bytes())
17 .expect("Failed to write error messages");
18 }));
19}