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
//! Errors in leetcode-cli
use std::fmt;
use std::error::Error as StdError;

/// Error enum
#[derive(Clone)]
pub enum Error {
    MatchError,
    DownloadError(String),
    NetworkError(String),
    ParseError(String),
    CacheError(String),
    FeatureError(String),
}

impl std::fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::CacheError(s) => {
                write!(f, "{:?}", error!("{}, please try again", s))
            },
            Error::DownloadError(s) => {
                write!(f, "Download {} failed, please try again", s)
            },
            Error::NetworkError(s) => {
                write!(f, "{:?}", error!("Network request {}, please try again", s))
            },
            Error::ParseError(s) => {
                write!(f, "{:?}", error!("{}, please try again", s))
            },
            Error::FeatureError(s) => {
                write!(f, "{:?}", error!("{}", s))
            }
            Error::MatchError => {
                write!(f, "{:?}", error!("Nothing matches"))
            },
        }
    }
}

// network
impl std::convert::From<reqwest::Error> for Error {
    fn from(err: reqwest::Error) -> Self {
        Error::NetworkError(err.description().to_string())
    }
}

// sql
impl std::convert::From<diesel::result::Error> for Error {
    fn from(err: diesel::result::Error) -> Self {
        Error::CacheError(err.description().to_string())
    }
}

impl std::convert::From<serde_json::error::Error> for Error {
    fn from(err: serde_json::Error) -> Self {
        Error::ParseError(err.description().to_string())
    }
}

// io
impl std::convert::From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        Error::CacheError(err.description().to_string())
    }
}

// options
impl std::convert::From<std::option::NoneError> for Error {
    fn from(_: std::option::NoneError) -> Self {
        Error::ParseError("json from response".to_string())
    }
}