panic_hook/
lib.rs

1// Copyright 2015-2020 Parity Technologies (UK) Ltd.
2// This file is part of Tetsy Vapory.
3
4// Tetsy Vapory is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Tetsy Vapory is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Tetsy Vapory.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Custom panic hook with bug report link
18
19extern crate backtrace;
20
21use std::panic::{self, PanicInfo};
22use std::thread;
23use std::process;
24use backtrace::Backtrace;
25
26/// Set the panic hook to write to stderr and abort the process when a panic happens.
27pub fn set_abort() {
28	set_with(|msg| {
29		eprintln!("{}", msg);
30		process::abort()
31	});
32}
33
34/// Set the panic hook with a closure to be called. The closure receives the panic message.
35///
36/// Depending on how Tetsy was compiled, after the closure has been executed, either the process
37/// aborts or unwinding starts.
38///
39/// If you panic within the closure, a double panic happens and the process will stop.
40pub 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}