mbar_rs/
errors.rs

1use pyo3::prelude::*;
2use thiserror::Error;
3
4/// Enum for errors in this crate
5#[derive(Error, Debug)]
6pub enum MBarError {
7    /// Error returned when MBarBuilder.build() was called improperly
8    #[error("Could not build MBar: {0}")]
9    BuilderError(String),
10
11    /// Error returned when a python exception is not handled
12    #[error("Unexpected Python exception was not handled")]
13    UnhandledPythonException {
14        #[allow(missing_docs)]
15        #[from]
16        source: PyErr,
17    },
18
19    /// Error returned when an array is the wrong length
20    #[error("Array of length {0} is incorrect; length should be {1}")]
21    ArrayLengthMismatch(usize, usize),
22
23    /// Error returned when an integer from Python fails to cast to usize
24    #[error("Unexpected Python exception was not handled")]
25    PythonNotUsize {
26        #[allow(missing_docs)]
27        #[from]
28        source: std::num::TryFromIntError,
29    },
30}
31
32impl MBarError {
33    /// Print the python error message, if present
34    pub fn print(&self) {
35        if let MBarError::UnhandledPythonException { source } = &self {
36            Python::with_gil(|py| source.print(py))
37        }
38    }
39}
40
41impl From<String> for MBarError {
42    fn from(s: String) -> Self {
43        Self::BuilderError(s)
44    }
45}
46
47/// Result type for the mbar-rs crate
48pub type Result<T> = std::result::Result<T, MBarError>;