Skip to main content

polars_python/
error.rs

1use std::error::Error;
2use std::fmt::{Debug, Display, Formatter};
3use std::io::ErrorKind;
4
5use polars::prelude::PolarsError;
6use polars_error::PolarsWarning;
7use pyo3::PyTypeInfo;
8use pyo3::exceptions::{
9    PyDeprecationWarning, PyFileExistsError, PyFileNotFoundError, PyIOError, PyPermissionError,
10    PyRuntimeError, PyUserWarning,
11};
12use pyo3::prelude::*;
13
14use crate::Wrap;
15use crate::exceptions::{
16    CategoricalRemappingWarning, ColumnNotFoundError, ComputeError, DuplicateError,
17    InvalidOperationError, MapWithoutReturnDtypeWarning, NoDataError, OutOfBoundsError,
18    SQLInterfaceError, SQLSyntaxError, SchemaError, SchemaFieldNotFoundError, ShapeError,
19    StringCacheMismatchError, StructFieldNotFoundError,
20};
21
22pub enum PyPolarsErr {
23    Polars(PolarsError),
24    Python(PyErr),
25    Other(String),
26}
27
28impl Error for PyPolarsErr {
29    fn source(&self) -> Option<&(dyn Error + 'static)> {
30        match self {
31            Self::Polars(err) => Some(err),
32            Self::Python(err) => Some(err),
33            Self::Other(_) => None,
34        }
35    }
36}
37
38impl std::fmt::Display for PyPolarsErr {
39    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
40        match self {
41            Self::Polars(err) => Display::fmt(err, f),
42            Self::Python(err) => Display::fmt(err, f),
43            Self::Other(err) => write!(f, "{err}"),
44        }
45    }
46}
47
48impl From<PolarsError> for PyPolarsErr {
49    fn from(err: PolarsError) -> Self {
50        PyPolarsErr::Polars(err)
51    }
52}
53
54impl From<PyErr> for PyPolarsErr {
55    fn from(err: PyErr) -> Self {
56        PyPolarsErr::Python(err)
57    }
58}
59
60impl From<PyPolarsErr> for PyErr {
61    fn from(err: PyPolarsErr) -> PyErr {
62        use PyPolarsErr::*;
63        match err {
64            Polars(err) => match err {
65                PolarsError::AssertionError(err) => {
66                    pyo3::exceptions::PyAssertionError::new_err(err.to_string())
67                },
68                PolarsError::ColumnNotFound(name) => ColumnNotFoundError::new_err(name.to_string()),
69                PolarsError::ComputeError(err) => ComputeError::new_err(err.to_string()),
70                PolarsError::Duplicate(err) => DuplicateError::new_err(err.to_string()),
71                PolarsError::InvalidOperation(err) => {
72                    InvalidOperationError::new_err(err.to_string())
73                },
74                PolarsError::IO { error, msg } => {
75                    let msg = if let Some(msg) = msg {
76                        msg.to_string()
77                    } else {
78                        error.to_string()
79                    };
80                    // This error might have an underlying PolarsError, so
81                    // if we can find one of those, use it instead.
82                    let mut source = error.source();
83                    while let Some(error) = source {
84                        if let Some(e) = error.downcast_ref::<PolarsError>() {
85                            return PyPolarsErr::Polars(e.to_owned()).into();
86                        }
87                        source = error.source();
88                    }
89                    match error.kind() {
90                        ErrorKind::NotFound => PyFileNotFoundError::new_err(msg),
91                        ErrorKind::PermissionDenied => PyPermissionError::new_err(msg),
92                        ErrorKind::AlreadyExists => PyFileExistsError::new_err(msg),
93                        _ => PyIOError::new_err(msg),
94                    }
95                },
96                PolarsError::NoData(err) => NoDataError::new_err(err.to_string()),
97                PolarsError::OutOfBounds(err) => OutOfBoundsError::new_err(err.to_string()),
98                PolarsError::SQLInterface(name) => SQLInterfaceError::new_err(name.to_string()),
99                PolarsError::SQLSyntax(name) => SQLSyntaxError::new_err(name.to_string()),
100                PolarsError::SchemaFieldNotFound(name) => {
101                    SchemaFieldNotFoundError::new_err(name.to_string())
102                },
103                PolarsError::SchemaMismatch(err) => SchemaError::new_err(err.to_string()),
104                PolarsError::ShapeMismatch(err) => ShapeError::new_err(err.to_string()),
105                PolarsError::StringCacheMismatch(err) => {
106                    StringCacheMismatchError::new_err(err.to_string())
107                },
108                PolarsError::StructFieldNotFound(name) => {
109                    StructFieldNotFoundError::new_err(name.to_string())
110                },
111                PolarsError::Context { .. } | PolarsError::ExprContext { .. } => {
112                    let tmp = PyPolarsErr::Polars(err.context_trace());
113                    PyErr::from(tmp)
114                },
115                PolarsError::Python { error } => error.0,
116            },
117            Python(err) => err,
118            err => PyRuntimeError::new_err(format!("{:?}", &err)),
119        }
120    }
121}
122
123impl Debug for PyPolarsErr {
124    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
125        use PyPolarsErr::*;
126        match self {
127            Polars(err) => write!(f, "{err:?}"),
128            Python(err) => write!(f, "{err:?}"),
129            Other(err) => write!(f, "BindingsError: {err:?}"),
130        }
131    }
132}
133
134#[macro_export]
135macro_rules! raise_err(
136    ($msg:expr, $err:ident) => {{
137        Err(PolarsError::$err($msg.into())).map_err(PyPolarsErr::from)?;
138        unreachable!()
139    }}
140);
141
142impl<'py> IntoPyObject<'py> for Wrap<PolarsWarning> {
143    type Target = PyAny;
144    type Output = Bound<'py, Self::Target>;
145    type Error = std::convert::Infallible;
146
147    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
148        match self.0 {
149            PolarsWarning::CategoricalRemappingWarning => {
150                Ok(CategoricalRemappingWarning::type_object(py).into_any())
151            },
152            PolarsWarning::MapWithoutReturnDtypeWarning => {
153                Ok(MapWithoutReturnDtypeWarning::type_object(py).into_any())
154            },
155            PolarsWarning::UserWarning => Ok(PyUserWarning::type_object(py).into_any()),
156            PolarsWarning::Deprecation => Ok(PyDeprecationWarning::type_object(py).into_any()),
157        }
158    }
159}