1use core::fmt;
2use std::{error::Error, fmt::Display};
3
4use reqwest::StatusCode;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum TeatimeErrorKind {
8 HttpError,
9 ParseError,
10 SerializationError,
11 Other,
12}
13
14impl Display for TeatimeErrorKind {
15 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
16 match self {
17 TeatimeErrorKind::HttpError => write!(f, "HTTP error"),
18 TeatimeErrorKind::ParseError => write!(f, "Parsing error"),
19 TeatimeErrorKind::SerializationError => write!(f, "Serialization error"),
20 TeatimeErrorKind::Other => write!(f, "error"),
21 }
22 }
23}
24
25#[derive(Debug, Clone)]
28pub struct TeatimeError {
29 pub message: String,
30 pub kind: TeatimeErrorKind,
31 pub status_code: reqwest::StatusCode,
32}
33impl Error for TeatimeError {}
34impl Display for TeatimeError {
35 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36 write!(f, "{}", self.message)
37 }
38}
39
40pub type Result<T> = std::result::Result<T, TeatimeError>;
43
44impl From<reqwest::Error> for TeatimeError {
48 fn from(err: reqwest::Error) -> Self {
49 let mut kind = TeatimeErrorKind::HttpError;
50 if err.is_decode() {
51 kind = TeatimeErrorKind::SerializationError;
52 }
53 TeatimeError {
54 message: format!("{}", err),
55 status_code: err.status().unwrap_or(StatusCode::BAD_REQUEST),
56 kind,
57 }
58 }
59}
60
61impl From<serde_json::Error> for TeatimeError {
62 fn from(err: serde_json::Error) -> Self {
63 TeatimeError {
64 message: format!("{}", err),
65 status_code: StatusCode::BAD_REQUEST,
66 kind: TeatimeErrorKind::ParseError,
67 }
68 }
69}
70
71impl From<Box<dyn Error>> for TeatimeError {
72 fn from(err: Box<dyn Error>) -> Self {
73 TeatimeError {
74 message: format!("{}", err),
75 status_code: StatusCode::BAD_REQUEST,
76 kind: TeatimeErrorKind::Other,
77 }
78 }
79}