1 | //! Helper to convert Rust panics to Python exceptions. |
2 | use crate::exceptions::PyBaseException; |
3 | use crate::PyErr; |
4 | use std::any::Any; |
5 | |
6 | pyo3_exception!( |
7 | " |
8 | The exception raised when Rust code called from Python panics. |
9 | |
10 | Like SystemExit, this exception is derived from BaseException so that |
11 | it will typically propagate all the way through the stack and cause the |
12 | Python interpreter to exit. |
13 | " , |
14 | PanicException, |
15 | PyBaseException |
16 | ); |
17 | |
18 | impl PanicException { |
19 | /// Creates a new PanicException from a panic payload. |
20 | /// |
21 | /// Attempts to format the error in the same way panic does. |
22 | #[cold ] |
23 | pub(crate) fn from_panic_payload(payload: Box<dyn Any + Send + 'static>) -> PyErr { |
24 | if let Some(string: &String) = payload.downcast_ref::<String>() { |
25 | Self::new_err((string.clone(),)) |
26 | } else if let Some(s: &&str) = payload.downcast_ref::<&str>() { |
27 | Self::new_err((s.to_string(),)) |
28 | } else { |
29 | Self::new_err(("panic from Rust code" ,)) |
30 | } |
31 | } |
32 | } |
33 | |