baichun_framework_rms/
error.rs1use rdkafka::error::KafkaError;
6use rdkafka::types::RDKafkaErrorCode;
7use std::fmt;
8
9#[derive(Debug, thiserror::Error)]
14pub enum Error {
15 #[error("Channel error: {0}")]
19 Channel(String),
20
21 #[error("Conversion error: {0}")]
25 Conversion(String),
26
27 #[error("Validation error: {0}")]
31 Validation(String),
32
33 #[error("Configuration error: {0}")]
37 Config(String),
38
39 #[error("Connection error: {0}")]
43 Connection(String),
44
45 #[error("Timeout error: {0}")]
49 Timeout(String),
50
51 #[error("Other error: {0}")]
55 Other(String),
56}
57
58impl Error {
59 pub fn channel<T: fmt::Display>(err: T) -> Self {
65 Self::Channel(err.to_string())
66 }
67
68 pub fn conversion<T: fmt::Display>(err: T) -> Self {
70 Self::Conversion(err.to_string())
71 }
72
73 pub fn validation<T: fmt::Display>(err: T) -> Self {
75 Self::Validation(err.to_string())
76 }
77
78 pub fn config<T: fmt::Display>(err: T) -> Self {
80 Self::Config(err.to_string())
81 }
82
83 pub fn connection<T: fmt::Display>(err: T) -> Self {
85 Self::Connection(err.to_string())
86 }
87
88 pub fn timeout<T: fmt::Display>(err: T) -> Self {
90 Self::Timeout(err.to_string())
91 }
92
93 pub fn other<T: fmt::Display>(err: T) -> Self {
95 Self::Other(err.to_string())
96 }
97
98 pub fn is_timeout(&self) -> bool {
100 matches!(self, Self::Timeout(_))
101 }
102
103 pub fn is_connection_error(&self) -> bool {
105 matches!(self, Self::Connection(_))
106 }
107}
108
109pub type Result<T> = std::result::Result<T, Error>;
111
112impl From<KafkaError> for Error {
114 fn from(err: KafkaError) -> Self {
115 match err {
116 KafkaError::Global(code) => match code {
117 RDKafkaErrorCode::MessageTimedOut => Self::Timeout(err.to_string()),
118 RDKafkaErrorCode::BrokerTransportFailure => Self::Connection(err.to_string()),
119 RDKafkaErrorCode::AllBrokersDown => Self::Connection(err.to_string()),
120 _ => Self::Other(err.to_string()),
121 },
122 _ => Self::Other(err.to_string()),
123 }
124 }
125}
126
127impl From<std::io::Error> for Error {
128 fn from(err: std::io::Error) -> Self {
129 match err.kind() {
130 std::io::ErrorKind::TimedOut => Self::Timeout(err.to_string()),
131 std::io::ErrorKind::ConnectionRefused
132 | std::io::ErrorKind::ConnectionReset
133 | std::io::ErrorKind::ConnectionAborted => Self::Connection(err.to_string()),
134 _ => Self::Other(err.to_string()),
135 }
136 }
137}
138
139impl From<serde_json::Error> for Error {
140 fn from(err: serde_json::Error) -> Self {
141 Self::Conversion(err.to_string())
142 }
143}
144
145impl From<tokio::sync::broadcast::error::SendError<()>> for Error {
146 fn from(err: tokio::sync::broadcast::error::SendError<()>) -> Self {
147 Self::Channel(err.to_string())
148 }
149}