I have the following code:
use std::thread;
use std::panic;
pub fn main(){
thread::spawn(move || {
panic::catch_unwind(|| {
// panic!("Oh no! A horrible error.");
let s: Option<u32> = None;
s.expect("Nothing was there!");
})
})
.join()
.and_then(|result| {
match result {
Ok(ref val) => {
println!("No problems. Result was: {:?}", val);
}
Err(ref err) => {
if let Some(err) = err.downcast_ref::<&'static str>() {
println!("Error: {}", err);
} else {
println!("Unknown error type: {:?}", err);
}
}
}
result
});
}
When I trigger a panic!
directly (by uncommenting the line in the code above), then I get an output which includes my error message:
Error: Oh no! A horrible error.
But, if I use Option::expect(&str)
, as above, then the message cannot be downcast to &'static str
, so I can't get the error message out:
Unknown error type: Any
How can I get the error message, and how would I find the correct type to downcast to in the general case?
panic!(my_str)
will end up being caught as aString
whenmy_str
is constructed at runtime. So the behaviour ofpanic!()
is actually exactly what you described as your "perhaps eventually" behaviour forOption::expect
. – Jobholder