-
Notifications
You must be signed in to change notification settings - Fork 783
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add catch_unwind! macro to prevent panics crossing ffi boundaries
- Loading branch information
1 parent
e9bec07
commit 2904fec
Showing
5 changed files
with
65 additions
and
5 deletions.
There are no files selected for viewing
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
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
use crate::exceptions::BaseException; | ||
use crate::Python; | ||
/// 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. | ||
pub struct PanicException { | ||
_private: (), | ||
} | ||
|
||
pyo3_exception!(PanicException, BaseException); | ||
|
||
#[macro_export] | ||
macro_rules! catch_unwind { | ||
($py:ident, $block:expr) => {{ | ||
match std::panic::catch_unwind(|| -> $crate::PyResult<_> { $block }) { | ||
Ok(result) => result, | ||
Err(e) => { | ||
// Try to format the error in the same way panic does | ||
if let Some(string) = e.downcast_ref::<String>() { | ||
Err($crate::panic::PanicException::py_err((string.clone(),))) | ||
} else if let Some(s) = e.downcast_ref::<&str>() { | ||
Err($crate::panic::PanicException::py_err((s.to_string(),))) | ||
} else { | ||
Err($crate::panic::PanicException::py_err(( | ||
"panic from Rust code", | ||
))) | ||
} | ||
} | ||
} | ||
}}; | ||
} | ||
|
||
impl std::panic::UnwindSafe for Python<'_> {} | ||
impl std::panic::RefUnwindSafe for Python<'_> {} |