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
use std::borrow::Cow;
use std::error::Error as StdError;
use thiserror::Error;

pub(crate) type BoxError = Box<dyn StdError + Send + Sync>;

#[derive(Error, Debug)]
#[error("Custom error message: {}", .msg)]
pub struct Error {
    kind: ErrorKind,
    msg: Cow<'static, str>,
    inner: Option<BoxError>,
}

impl Error {
    pub fn new<M: Into<Cow<'static, str>>>(kind: ErrorKind, msg: M) -> Error {
        Error {
            kind,
            msg: msg.into(),
            inner: None,
        }
    }
    pub fn new_with_inner<M: Into<Cow<'static, str>>>(
        kind: ErrorKind,
        msg: M,
        inner: BoxError,
    ) -> Error {
        Error {
            kind,
            msg: msg.into(),
            inner: inner.into(),
        }
    }
}

impl From<reqwest::Error> for Error {
    fn from(err: reqwest::Error) -> Error {
        let kind = if err.is_timeout() {
            ErrorKind::Timeout
        } else {
            ErrorKind::Unknown
        };

        Error::new_with_inner(kind, err.to_string(), err.into())
    }
}

#[derive(Debug)]
pub enum ErrorKind {
    Unknown,
    Timeout,
    Unauthorized,
}