Elffuss BraidHub

kikocis/lancedb public

bbc8a2ecbe2c · 2.2 KiBRawPermalink
1// Copyright 2024 Lance Developers.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use pyo3::{
16 exceptions::{PyIOError, PyNotImplementedError, PyOSError, PyRuntimeError, PyValueError},
17 PyResult,
18};
19
20use lancedb::error::Error as LanceError;
21
22pub trait PythonErrorExt<T> {
23 /// Convert to a python error based on the Lance error type
24 fn infer_error(self) -> PyResult<T>;
25 /// Convert to OSError
26 fn os_error(self) -> PyResult<T>;
27 /// Convert to RuntimeError
28 fn runtime_error(self) -> PyResult<T>;
29 /// Convert to ValueError
30 fn value_error(self) -> PyResult<T>;
31}
32
33impl<T> PythonErrorExt<T> for std::result::Result<T, LanceError> {
34 fn infer_error(self) -> PyResult<T> {
35 match &self {
36 Ok(_) => Ok(self.unwrap()),
37 Err(err) => match err {
38 LanceError::InvalidInput { .. }
39 | LanceError::InvalidTableName { .. }
40 | LanceError::TableNotFound { .. }
41 | LanceError::Schema { .. } => self.value_error(),
42 LanceError::CreateDir { .. } => self.os_error(),
43 LanceError::ObjectStore { .. } => Err(PyIOError::new_err(err.to_string())),
44 LanceError::NotSupported { .. } => {
45 Err(PyNotImplementedError::new_err(err.to_string()))
46 }
47 _ => self.runtime_error(),
48 },
49 }
50 }
51
52 fn os_error(self) -> PyResult<T> {
53 self.map_err(|err| PyOSError::new_err(err.to_string()))
54 }
55
56 fn runtime_error(self) -> PyResult<T> {
57 self.map_err(|err| PyRuntimeError::new_err(err.to_string()))
58 }
59
60 fn value_error(self) -> PyResult<T> {
61 self.map_err(|err| PyValueError::new_err(err.to_string()))
62 }
63}