Skip to main content

zenkit/
error.rs

1use crate::types::ErrorInfo;
2use std::fmt;
3
4/// Errors returned by this crate
5#[derive(Debug)]
6pub enum Error {
7    /// Error returned from Zenkit: (http status, optional zenkit-defined error code)
8    ApiError(u16, Option<ErrorInfo>),
9    /// Error serializing or deserializing json data
10    JsonError(String),
11    /// Network error (reported by reqwest http client)
12    //NetError(String),
13    /// Invalid utf-8 (converting binary to text)
14    Utf8Error(String),
15    /// URL parsing error
16    ParseError(String),
17    /// IO error - used for verbose http logging to files
18    IoError(String),
19    /// Error returned by reqwest library
20    Reqwest(reqwest::Error),
21
22    /// assumed single-value category field but multiple values were set
23    /// First param is general message, second is field name
24    MultiCategory(String, String),
25
26    /// Api token has not been set
27    MissingApiToken(String),
28
29    /// Error if static object is already initialized
30    AlreadyInitialized,
31    /// Error if static initializer was not called before getter
32    NotInitialized,
33
34    /// Error that doesn't fit any of the above
35    Other(String),
36}
37
38impl Error {
39    /// Returns true if the error means a rate limit has been hit
40    pub fn is_rate_limit(&self) -> bool {
41        if let Error::ApiError(_, Some(info)) = self {
42            if &info.code == "D1" || &info.code == "D2" {
43                return true;
44            }
45        }
46        false
47    }
48}
49
50impl std::error::Error for Error {}
51
52impl From<serde_json::Error> for Error {
53    fn from(e: serde_json::Error) -> Self {
54        Error::JsonError(format!("serde_json: {:?}", e))
55    }
56}
57
58impl From<reqwest::Error> for Error {
59    fn from(e: reqwest::Error) -> Self {
60        Error::Reqwest(e)
61    }
62}
63
64impl From<std::io::Error> for Error {
65    fn from(e: std::io::Error) -> Self {
66        Error::IoError(format!("{:?}", e))
67    }
68}
69
70impl From<std::str::Utf8Error> for Error {
71    fn from(e: std::str::Utf8Error) -> Self {
72        Error::Utf8Error(format!("Invalid UTF-8: {}", e.to_string()))
73    }
74}
75
76impl<T> From<std::sync::PoisonError<T>> for Error {
77    fn from(e: std::sync::PoisonError<T>) -> Self {
78        Error::Other(format!(
79            "Thread died while holding lock. Sorry, you need to quit and start over: {}",
80            e
81        ))
82    }
83}
84
85impl fmt::Display for Error {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        write!(f, "{:#?}", self)
88    }
89}