kafka_http/
error.rs

1use std::fmt::Display;
2use serde::{Deserialize, Serialize};
3
4/// This enum is used to categorize errors that occur in the application and provide a consistent
5/// way to handle and report errors. Each error type has a corresponding message that can be used.
6#[derive(Debug, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq, Clone)]
7pub enum ErrorType {
8    ParseError,
9    ThirdPartyError,
10    MissingConfig,
11    UnknownError,
12    InternalError,
13    TimeoutError,
14    IoError,
15    NotFound,
16    InvalidInput,
17}
18
19#[derive(Debug, Serialize, Deserialize, Clone)]
20pub struct Error {
21    pub error_type: ErrorType,
22    pub message: String,
23}
24
25impl Error {
26    pub fn internal(p0: &str) -> Self {
27        Error {
28            error_type: ErrorType::InternalError,
29            message: p0.to_string()
30        }
31    }
32
33    pub fn input(p0: &str) -> Self {
34        Error {
35            error_type: ErrorType::InternalError,
36            message: p0.to_string()
37        }
38    }
39
40    pub fn api(p0: &str) -> Self {
41        Error {
42            error_type: ErrorType::ThirdPartyError,
43            message: p0.to_string()
44        }
45    }
46}
47
48impl Error {
49    pub fn new(error_type: ErrorType, message: &str) -> Self {
50        Error {
51            error_type,
52            message: message.to_string(),
53        }
54    }
55}
56
57impl Display for Error {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        write!(f, "{:?}: {}", self.error_type, self.message)
60    }
61}
62
63impl From<String> for Error {
64    fn from(error: String) -> Self {
65        Error {
66            error_type: ErrorType::ThirdPartyError,
67            message: error.to_string(),
68        }
69    }
70}
71
72impl From<reqwest::Error> for Error {
73    fn from(error: reqwest::Error) -> Self {
74        Error {
75            error_type: ErrorType::ThirdPartyError,
76            message: error.to_string(),
77        }
78    }
79}
80
81impl From<serde_json::error::Error> for Error {
82    fn from(error: serde_json::error::Error) -> Self {
83        Error {
84            error_type: ErrorType::ParseError,
85            message: error.to_string(),
86        }
87    }
88}
89
90impl std::error::Error for Error {
91    fn description(&self) -> &str {
92        &self.message
93    }
94}