pyo3/src/panic.rs

30 lines
933 B
Rust
Raw Normal View History

2021-06-30 10:03:53 +00:00
//! Helper to convert Rust panics to Python exceptions.
use crate::exceptions::PyBaseException;
use crate::PyErr;
use std::any::Any;
2020-05-24 12:38:27 +00:00
pyo3_exception!(
"
The exception raised when Rust code called from Python panics.
Like SystemExit, this exception is derived from BaseException so that
it will typically propagate all the way through the stack and cause the
Python interpreter to exit.
",
PanicException,
PyBaseException
);
impl PanicException {
// Try to format the error in the same way panic does
2021-05-15 09:33:17 +00:00
pub(crate) fn from_panic_payload(payload: Box<dyn Any + Send + 'static>) -> PyErr {
if let Some(string) = payload.downcast_ref::<String>() {
Self::new_err((string.clone(),))
2021-05-15 09:33:17 +00:00
} else if let Some(s) = payload.downcast_ref::<&str>() {
Self::new_err((s.to_string(),))
} else {
Self::new_err(("panic from Rust code",))
}
}
}