1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use reqwest::Error;
use serde::export::Formatter;
use serde::Deserialize;
use std::collections::HashMap;
use std::error::Error as StdError;
use std::fmt;

#[derive(Debug, PartialEq)]
pub enum Kind {
    ServiceError,
    TooManyRequests,
    PaymentRequired,
    UnprocessableEntity,
    Forbidden,
    EntityDoesNotExists,
    Unauthorized,
    Other,
}

#[derive(Debug)]
pub struct UnknownError(String);

impl UnknownError {
    pub(crate) fn new(fn_name: &str) -> Self {
        Self(fn_name.to_string())
    }
}

impl fmt::Display for UnknownError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("Something is wrong in function {}", self.0))
    }
}

impl StdError for UnknownError {}

#[derive(Deserialize)]
pub(crate) struct DataErrors {
    errors: HashMap<String, Vec<String>>,
}

/// If something goes wrong this error wil bew returned.
#[derive(Debug)]
pub struct FakturoidError {
    kind: Kind,
    inner_request: Option<Error>,
    inner_other: Option<Box<dyn StdError>>,
    data_errors: Option<HashMap<String, Vec<String>>>,
}

impl FakturoidError {
    /// Transforms this object into underlying error from reqwest library if there is any.
    pub fn into_request_err(self) -> Option<Error> {
        self.inner_request
    }

    /// Transforms this object into std::error::Error.
    pub fn into_std_err(self) -> Box<dyn StdError> {
        assert!(
            self.inner_request.is_some() || self.inner_other.is_some(),
            "There is no inner error!"
        );
        if let Some(req_err) = self.inner_request {
            req_err.into()
        } else {
            self.inner_other.unwrap()
        }
    }

    /// Error kind.
    pub fn kind(&self) -> &Kind {
        &self.kind
    }

    /// If fakturoid.cz API returns JSON with errors (status 422) method transforms this object
    /// into `HashMap` of these errors otherwise `None` will be returned.
    pub fn into_data_errors(self) -> Option<HashMap<String, Vec<String>>> {
        self.data_errors
    }

    /// If fakturoid.cz API returns JSON with errors (status 422) method returns reference to
    /// `HashMap` of these errors otherwise `None` will be returned.
    pub fn data_errors(&self) -> Option<&HashMap<String, Vec<String>>> {
        self.data_errors.as_ref()
    }

    pub(crate) fn from_std_err<E>(err: E) -> Self
    where
        E: StdError + 'static,
    {
        Self {
            kind: Kind::Other,
            inner_request: None,
            inner_other: Some(err.into()),
            data_errors: None,
        }
    }

    pub(crate) fn from_data(data: DataErrors, err: Error) -> Self {
        Self {
            kind: Kind::UnprocessableEntity,
            inner_request: Some(err),
            inner_other: None,
            data_errors: Some(data.errors),
        }
    }
}

impl From<Error> for FakturoidError {
    fn from(err: Error) -> Self {
        let mut kind = Kind::Other;
        if let Some(status) = err.status() {
            if status.is_server_error() {
                kind = Kind::ServiceError;
            }
            if status.as_u16() == 429 {
                kind = Kind::TooManyRequests;
            }
            if status.as_u16() == 402 {
                kind = Kind::PaymentRequired;
            }
            if status.as_u16() == 422 {
                kind = Kind::UnprocessableEntity;
            }
            if status.as_u16() == 403 {
                kind = Kind::Forbidden;
            }
            if status.as_u16() == 404 {
                kind = Kind::EntityDoesNotExists;
            }
            if status.as_u16() == 401 {
                kind = Kind::Unauthorized;
            }
        }
        Self {
            kind,
            inner_request: Some(err),
            inner_other: None,
            data_errors: None,
        }
    }
}

impl fmt::Display for FakturoidError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self.kind {
            Kind::ServiceError => {
                if let Some(req_err) = self.inner_request.as_ref() {
                    f.write_fmt(format_args!(
                        "Service Unavailable. Status is: {}",
                        req_err.status().as_ref().unwrap()
                    ))
                } else {
                    f.write_str("Service error")
                }
            }
            Kind::TooManyRequests => {
                f.write_str("Request limit exceeded. Limit is 200 per one minute.")
            }
            Kind::PaymentRequired => f.write_str("Payment required"),
            Kind::UnprocessableEntity => {
                if let Some(errs) = self.data_errors.as_ref() {
                    f.write_fmt(format_args!("Errors in input data: {:?}", errs))
                } else {
                    f.write_str("Malformed input data.")
                }
            },
            Kind::Forbidden => f.write_str("Forbidden operation"),
            Kind::EntityDoesNotExists => f.write_str("Entity does not exists"),
            Kind::Unauthorized => f.write_str("Operation is not authorized. Check credentials"),
            Kind::Other => {
                assert!(
                    self.inner_request.is_some() || self.inner_other.is_some(),
                    "There is no inner error!"
                );
                if let Some(req_err) = self.inner_request.as_ref() {
                    req_err.fmt(f)
                } else {
                    self.inner_other.as_ref().unwrap().fmt(f)
                }
            }
        }
    }
}

impl StdError for FakturoidError {}