1extern crate backtrace;
20
21use std::panic::{self, PanicInfo};
22use std::thread;
23use std::process;
24use backtrace::Backtrace;
25
26pub fn set_abort() {
28 set_with(|msg| {
29 eprintln!("{}", msg);
30 process::abort()
31 });
32}
33
34pub fn set_with<F>(f: F)
41where F: Fn(&str) + Send + Sync + 'static
42{
43 panic::set_hook(Box::new(move |info| {
44 let msg = gen_panic_msg(info);
45 f(&msg);
46 }));
47}
48
49static ABOUT_PANIC: &str = "
50This is a bug. Please report it at:
51
52 https://github.com/openvapory/tetsy-vapory/issues/new
53";
54
55fn gen_panic_msg(info: &PanicInfo) -> String {
56 let location = info.location();
57 let file = location.as_ref().map(|l| l.file()).unwrap_or("<unknown>");
58 let line = location.as_ref().map(|l| l.line()).unwrap_or(0);
59
60 let msg = match info.payload().downcast_ref::<&'static str>() {
61 Some(s) => *s,
62 None => match info.payload().downcast_ref::<String>() {
63 Some(s) => &s[..],
64 None => "Box<Any>",
65 }
66 };
67
68 let thread = thread::current();
69 let name = thread.name().unwrap_or("<unnamed>");
70
71 let backtrace = Backtrace::new();
72
73 format!(r#"
74
75====================
76
77{backtrace:?}
78
79Thread '{name}' panicked at '{msg}', {file}:{line}
80{about}
81"#, backtrace = backtrace, name = name, msg = msg, file = file, line = line, about = ABOUT_PANIC)
82}