Skip to main content

serialplugin_core/
error.rs

1#[cfg(target_os = "ios")]
2use crate::serialport;
3use serde::{Serialize, Serializer};
4use std::io;
5
6/// An error type for serial port operations
7#[derive(Debug)]
8pub enum Error {
9    /// IO Error (stored as string to allow cloning)
10    Io(String),
11    /// String error message
12    String(String),
13    /// Serial port error
14    SerialPort(String),
15}
16
17impl Clone for Error {
18    fn clone(&self) -> Self {
19        match self {
20            Error::Io(s) => Error::Io(s.clone()),
21            Error::String(s) => Error::String(s.clone()),
22            Error::SerialPort(s) => Error::SerialPort(s.clone()),
23        }
24    }
25}
26
27impl Error {
28    pub fn new(msg: impl Into<String>) -> Self {
29        Error::String(msg.into())
30    }
31}
32
33impl std::fmt::Display for Error {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        match self {
36            Error::Io(err) => write!(f, "IO error: {}", err),
37            Error::String(s) => write!(f, "{}", s),
38            Error::SerialPort(err) => write!(f, "Serial port error: {}", err),
39        }
40    }
41}
42
43impl std::error::Error for Error {
44    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
45        match self {
46            Error::Io(_) => None,
47            Error::SerialPort(_) => None,
48            Error::String(_) => None,
49        }
50    }
51}
52
53impl From<io::Error> for Error {
54    fn from(err: io::Error) -> Self {
55        Error::Io(err.to_string())
56    }
57}
58
59impl From<serialport::Error> for Error {
60    fn from(err: serialport::Error) -> Self {
61        Error::SerialPort(err.to_string())
62    }
63}
64
65impl From<&str> for Error {
66    fn from(err: &str) -> Self {
67        Error::String(err.to_string())
68    }
69}
70
71impl From<String> for Error {
72    fn from(err: String) -> Self {
73        Error::String(err)
74    }
75}
76
77/// 4.0.0 API on Android (feature `tauri`, enabled by the plugin).
78#[cfg(all(target_os = "android", feature = "tauri"))]
79impl From<tauri::plugin::mobile::PluginInvokeError> for Error {
80    fn from(error: tauri::plugin::mobile::PluginInvokeError) -> Self {
81        Error::String(error.to_string())
82    }
83}
84
85impl From<Error> for io::Error {
86    fn from(error: Error) -> io::Error {
87        match error {
88            Error::Io(e) => io::Error::other(e),
89            Error::String(s) => io::Error::other(s),
90            Error::SerialPort(e) => io::Error::other(e),
91        }
92    }
93}
94
95impl Serialize for Error {
96    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
97    where
98        S: Serializer,
99    {
100        serializer.serialize_str(&self.to_string())
101    }
102}