-
-
Notifications
You must be signed in to change notification settings - Fork 470
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Trap panics and silence bad pipe errors (#862)
- Loading branch information
Showing
4 changed files
with
59 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
use std::any::Any; | ||
use std::{panic, process}; | ||
|
||
fn is_bad_pipe(payload: &dyn Any) -> bool { | ||
payload | ||
.downcast_ref::<String>() | ||
.map_or(false, |x| x.contains("failed printing to stdout: ")) | ||
} | ||
|
||
/// Registers a panic hook that hides stdout printing failures. | ||
pub fn set_panic_hook() { | ||
let default_hook = panic::take_hook(); | ||
panic::set_hook(Box::new(move |info| { | ||
if !is_bad_pipe(info.payload()) { | ||
default_hook(info) | ||
} | ||
})); | ||
} | ||
|
||
/// Catches down panics that are caused by bad pipe errors. | ||
pub fn trap_bad_pipe<F: FnOnce() -> i32 + Send + Sync>(f: F) -> ! { | ||
process::exit(match panic::catch_unwind(panic::AssertUnwindSafe(f)) { | ||
Ok(status) => status, | ||
Err(panic) => { | ||
if is_bad_pipe(&panic) { | ||
1 | ||
} else { | ||
panic::resume_unwind(panic); | ||
} | ||
} | ||
}); | ||
} |