Skip to content

Commit

Permalink
feat(panic): Add basic panic handler and installation function
Browse files Browse the repository at this point in the history
Fixes: #22
  • Loading branch information
zkat committed Sep 21, 2021
1 parent 89ba248 commit 11a708a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub use eyreish::*;
pub use handler::*;
pub use handlers::*;
pub use named_source::*;
pub use panic::*;
pub use protocol::*;

mod chain;
Expand All @@ -19,5 +20,6 @@ mod eyreish;
mod handler;
mod handlers;
mod named_source;
mod panic;
mod protocol;
mod source_impls;
30 changes: 30 additions & 0 deletions src/panic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use thiserror::Error;

use crate::{self as miette, Context, Diagnostic, Result};

/// Tells miette to render panics using its rendering engine.
pub fn set_panic_hook() {
std::panic::set_hook(Box::new(|info| {
let mut message = "Something went wrong".to_string();
let payload = info.payload();
if let Some(msg) = payload.downcast_ref::<&str>() {
message = msg.to_string();
}
if let Some(msg) = payload.downcast_ref::<String>() {
message = msg.clone();
}
let mut report: Result<()> = Err(Panic(message).into());
if let Some(loc) = info.location() {
report = report
.with_context(|| format!("at {}:{}:{}", loc.file(), loc.line(), loc.column()));
}
if let Err(err) = report.with_context(|| "Main thread panicked.".to_string()) {
eprintln!("Error: {:?}", err);
}
}));
}

#[derive(Debug, Error, Diagnostic)]
#[error("{0}")]
#[diagnostic(help("set the `RUST_BACKTRACE=1` environment variable to display a backtrace."))]
struct Panic(String);

0 comments on commit 11a708a

Please sign in to comment.