Can I custom the panic handling method? #1791
Answered
by
the10thWiz
zemelLeong
asked this question in
Questions
-
When the panic occoured. I want to use the panic message as response data. Is there any entrance to Rocket that can be handled uniformly. fn main() {
use std::any::Any;
use std::ops::Deref;
pub fn get_panic_message(panic: &Box<dyn Any + Send>) -> Option<&str> {
panic
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| panic.downcast_ref::<&'static str>().map(Deref::deref))
}
fn get_message() {
use std::panic;
let result = panic::catch_unwind(|| {
let a: Option<i32> = None;
let b = a.expect("Error message for response.");
b
});
if result.is_err() {
let err_result = result.expect_err("msg");
let message = get_panic_message(&err_result);
println!("{:?}=================", message);
}
}
get_message();
} |
Beta Was this translation helpful? Give feedback.
Answered by
the10thWiz
Jul 28, 2021
Replies: 2 comments
-
Panicking is not normal, and should not be treated as such. As the error message notes, Panicking causes unwinding, which is an expensive operation. Your code should NEVER panic; if an error condition is recoverable you should return Option or Result, which provides full control over the error message provided. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
zemelLeong
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Panicking is not normal, and should not be treated as such. As the error message notes, Panicking causes unwinding, which is an expensive operation. Your code should NEVER panic; if an error condition is recoverable you should return Option or Result, which provides full control over the error message provided.