Skip to content

Instantly share code, notes, and snippets.

@alexcrichton
Created November 6, 2020 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexcrichton/3a46abcba484cf6f923230a97a216803 to your computer and use it in GitHub Desktop.
Save alexcrichton/3a46abcba484cf6f923230a97a216803 to your computer and use it in GitHub Desktop.
use std::panic;
// Goal: Use catch_unwind() and extract the panic message from the result.
//
fn main() {
let result = panic::catch_unwind(|| {
panic!("oh no!");
});
assert!(result.is_err());
match result {
Ok(_) => println!("OK!"),
Err(r) => match r
.downcast_ref::<String>()
.map(|s| s.as_str())
.or_else(|| r.downcast_ref::<&'static str>().cloned())
{
Some(as_string) => {
println!("Some case: ({}): {}", as_string.len(), as_string);
}
None => {
println!("None case: {:?}", r);
}
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment