1use std::fmt;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum ErrorKind {
13 Type,
15 Syntax,
17 InvalidAccess,
19 InvalidState,
21 Operation,
23 InvalidModification,
25 NotSupported,
27 NotCapable,
30 Internal,
33}
34
35impl ErrorKind {
36 pub fn name(self) -> &'static str {
39 match self {
40 ErrorKind::Type => "TypeError",
41 ErrorKind::Syntax => "SyntaxError",
42 ErrorKind::InvalidAccess => "InvalidAccessError",
43 ErrorKind::InvalidState => "InvalidStateError",
44 ErrorKind::Operation => "OperationError",
45 ErrorKind::InvalidModification => "InvalidModificationError",
46 ErrorKind::NotSupported => "NotSupportedError",
47 ErrorKind::NotCapable => "NotCapable",
48 ErrorKind::Internal => "Error",
49 }
50 }
51}
52
53#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct Error {
56 pub kind: ErrorKind,
57 pub message: String,
58}
59
60impl Error {
61 pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
62 Self {
63 kind,
64 message: message.into(),
65 }
66 }
67
68 pub fn not_capable(message: impl Into<String>) -> Self {
71 Self::new(ErrorKind::NotCapable, message)
72 }
73
74 pub fn kind(&self) -> ErrorKind {
75 self.kind
76 }
77
78 pub fn message(&self) -> &str {
79 &self.message
80 }
81}
82
83impl fmt::Display for Error {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 f.write_str(&self.message)
86 }
87}
88
89impl std::error::Error for Error {}
90
91impl serde::Serialize for Error {
94 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
95 use serde::ser::SerializeStruct;
96 let mut st = s.serialize_struct("Error", 2)?;
97 st.serialize_field("kind", self.kind.name())?;
98 st.serialize_field("message", &self.message)?;
99 st.end()
100 }
101}
102
103pub type Result<T, E = Error> = std::result::Result<T, E>;