pytauri_core/
utils.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use std::error::Error;
use std::fmt::{Display, Formatter};

use pyo3::exceptions::PyRuntimeError;
use pyo3::prelude::*;

/// Utility for converting [tauri::Error] to [pyo3::PyErr].
///
/// See also: <https://pyo3.rs/v0.23.2/function/error-handling.html#foreign-rust-error-types>.
///
/// # Example
///
/**
```rust
use pyo3::prelude::*;
use pytauri_core::utils::{TauriError, TauriResult};

fn tauri_result() -> tauri::Result<()> {
    Ok(())
}

#[pyfunction]
fn foo() -> PyResult<()> {
    tauri_result().map_err(Into::<TauriError>::into)?;
    Ok(())
}

#[pyfunction]
fn bar() -> TauriResult<()> {
    tauri_result()?;
    Ok(())
}
```
*/

#[derive(Debug)]
pub struct TauriError(tauri::Error);

impl Display for TauriError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:}", self.0)
    }
}

impl Error for TauriError {}

impl From<TauriError> for PyErr {
    fn from(value: TauriError) -> Self {
        PyRuntimeError::new_err(format!("{:?}", value.0))
    }
}

impl From<tauri::Error> for TauriError {
    fn from(value: tauri::Error) -> Self {
        Self(value)
    }
}

pub type TauriResult<T> = Result<T, TauriError>;