rbatis_codegen/
error.rs

1use std::error::Error as StdError;
2use std::fmt::{self, Debug, Display};
3use std::io;
4
5use serde::de::Visitor;
6use serde::ser::{Serialize, Serializer};
7use serde::{Deserialize, Deserializer};
8
9pub type Result<T> = std::result::Result<T, Error>;
10
11/// Error
12#[derive(Debug)]
13#[non_exhaustive]
14pub enum Error {
15    /// Default Error
16    E(String),
17}
18
19impl Display for Error {
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        match self {
22            Error::E(error) => write!(f, "{}", error),
23        }
24    }
25}
26
27impl From<syn::Error> for Error {
28    fn from(value: syn::Error) -> Self {
29        Error::from(value.to_string())
30    }
31}
32impl StdError for Error {}
33
34impl From<io::Error> for Error {
35    #[inline]
36    fn from(err: io::Error) -> Self {
37        Error::from(err.to_string())
38    }
39}
40
41impl From<&str> for Error {
42    fn from(arg: &str) -> Self {
43        return Error::from(arg.to_string());
44    }
45}
46
47impl From<std::string::String> for Error {
48    fn from(arg: String) -> Self {
49        return Error::E(arg);
50    }
51}
52
53impl From<&dyn std::error::Error> for Error {
54    fn from(arg: &dyn std::error::Error) -> Self {
55        return Error::from(arg.to_string());
56    }
57}
58
59impl Clone for Error {
60    fn clone(&self) -> Self {
61        Error::from(self.to_string())
62    }
63
64    fn clone_from(&mut self, source: &Self) {
65        *self = Self::from(source.to_string());
66    }
67}
68
69// This is what #[derive(Serialize)] would generate.
70impl Serialize for Error {
71    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
72    where
73        S: Serializer,
74    {
75        serializer.serialize_str(self.to_string().as_str())
76    }
77}
78
79struct ErrorVisitor;
80
81impl<'de> Visitor<'de> for ErrorVisitor {
82    type Value = String;
83
84    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
85        formatter.write_str("a string")
86    }
87
88    fn visit_string<E>(self, v: String) -> std::result::Result<Self::Value, E>
89    where
90        E: std::error::Error,
91    {
92        Ok(v)
93    }
94
95    fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
96    where
97        E: std::error::Error,
98    {
99        Ok(v.to_string())
100    }
101}
102
103impl<'de> Deserialize<'de> for Error {
104    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
105    where
106        D: Deserializer<'de>,
107    {
108        let r = deserializer.deserialize_string(ErrorVisitor)?;
109        return Ok(Error::from(r));
110    }
111}