zng_ext_hot_reload/
util.rs

1use std::fmt;
2
3use zng_txt::{ToTxt, Txt};
4
5// format panic, code copied from `zng::crash_handler`
6pub fn crash_handler(info: &std::panic::PanicHookInfo) {
7    let backtrace = std::backtrace::Backtrace::capture();
8    let panic = PanicInfo::from_hook(info);
9    eprintln!("{panic}stack backtrace:\n{backtrace}");
10}
11
12#[derive(Debug)]
13struct PanicInfo {
14    pub thread: Txt,
15    pub msg: Txt,
16    pub file: Txt,
17    pub line: u32,
18    pub column: u32,
19}
20impl PanicInfo {
21    pub fn from_hook(info: &std::panic::PanicHookInfo) -> Self {
22        let current_thread = std::thread::current();
23        let thread = current_thread.name().unwrap_or("<unnamed>");
24        let msg = Self::payload(info.payload());
25
26        let (file, line, column) = if let Some(l) = info.location() {
27            (l.file(), l.line(), l.column())
28        } else {
29            ("<unknown>", 0, 0)
30        };
31        Self {
32            thread: thread.to_txt(),
33            msg,
34            file: file.to_txt(),
35            line,
36            column,
37        }
38    }
39
40    fn payload(p: &dyn std::any::Any) -> Txt {
41        match p.downcast_ref::<&'static str>() {
42            Some(s) => s,
43            None => match p.downcast_ref::<String>() {
44                Some(s) => &s[..],
45                None => "Box<dyn Any>",
46            },
47        }
48        .to_txt()
49    }
50}
51impl std::error::Error for PanicInfo {}
52impl fmt::Display for PanicInfo {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        writeln!(
55            f,
56            "thread '{}' panicked at {}:{}:{}:",
57            self.thread, self.file, self.line, self.column
58        )?;
59        for line in self.msg.lines() {
60            writeln!(f, "   {line}")?;
61        }
62        Ok(())
63    }
64}