serialplugin_core/
error.rs1#[cfg(target_os = "ios")]
2use crate::serialport;
3use serde::{Serialize, Serializer};
4use std::io;
5
6#[derive(Debug)]
8pub enum Error {
9 Io(String),
11 String(String),
13 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#[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}