Created
November 6, 2020 16:21
-
-
Save alexcrichton/3a46abcba484cf6f923230a97a216803 to your computer and use it in GitHub Desktop.
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
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