From b329fefc844c4c09b647ab8c47ab5015a3ad40a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jesper=20H=C3=A5kansson?= Date: Sat, 23 Mar 2019 13:44:56 +0100 Subject: [PATCH] feat: Print unexpected panics to standard error This will print to standard error for unexpected panics and then let `human_panic` handle panics, just like before. --- src/main.rs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index c99f5af0..2ad82952 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,13 +2,13 @@ extern crate atty; extern crate env_logger; #[macro_use] extern crate failure; -#[macro_use] extern crate human_panic; extern crate structopt; extern crate wasm_pack; extern crate which; use std::env; +use std::panic; use structopt::StructOpt; use wasm_pack::{command::run_wasm_pack, Cli}; @@ -16,7 +16,9 @@ mod installer; fn main() { env_logger::init(); - setup_panic!(); + + setup_panic_hooks(); + if let Err(e) = run() { eprintln!("Error: {}", e); for cause in e.iter_causes() { @@ -49,3 +51,29 @@ fn run() -> Result<(), failure::Error> { run_wasm_pack(args.cmd)?; Ok(()) } + +fn setup_panic_hooks() { + let meta = human_panic::Metadata { + version: env!("CARGO_PKG_VERSION").into(), + name: env!("CARGO_PKG_NAME").into(), + authors: env!("CARGO_PKG_AUTHORS").replace(":", ", ").into(), + homepage: env!("CARGO_PKG_HOMEPAGE").into(), + }; + + let default_hook = panic::take_hook(); + + match env::var("RUST_BACKTRACE") { + Err(_) => { + panic::set_hook(Box::new(move |info: &panic::PanicInfo| { + // First call the default hook that prints to standard error. + default_hook(info); + + // Then call human_panic. + let file_path = human_panic::handle_dump(&meta, info); + human_panic::print_msg(file_path, &meta) + .expect("human-panic: printing error message to console failed"); + })); + } + Ok(_) => {} + } +}