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
use hyper::StatusCode;
use std::{
    error::Error,
    fmt::{self, Display, Formatter},
};

/// Represents possible errors whic may occur while downloading a file.
#[derive(Debug)]
pub enum Download {
    /// The provided file had the `path` field set to `None`.
    NoPath,
    /// A network error.
    Network(hyper::Error),
    /// Telegram returned a different from 200 status code.
    InvalidStatusCode(StatusCode),
}

impl Download {
    /// Checks if `self` is `NoPath`.
    pub fn is_no_path(&self) -> bool {
        match self {
            Download::NoPath => true,
            _ => false,
        }
    }

    /// Checks if `self` is `Network`.
    pub fn is_network(&self) -> bool {
        match self {
            Download::Network(..) => true,
            _ => false,
        }
    }

    /// Checks if `self` is `InvalidStatusCode`.
    pub fn is_invalid_status_code(&self) -> bool {
        match self {
            Download::InvalidStatusCode(..) => true,
            _ => false,
        }
    }
}

impl Display for Download {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        match self {
            Download::NoPath => write!(
                formatter,
                "A file could not be downloaded because of missing `path`.",
            ),
            Download::Network(error) => write!(
                formatter,
                "A file could not be downloaded because of a network error: {}",
                error,
            ),
            Download::InvalidStatusCode(code) => write!(
                formatter,
                "A file could not be downloaded because Telegram responded \
                 with {} instead of 200 OK.",
                code,
            ),
        }
    }
}

impl Error for Download {}

impl From<hyper::Error> for Download {
    fn from(error: hyper::Error) -> Self {
        Download::Network(error)
    }
}

impl From<StatusCode> for Download {
    fn from(error: StatusCode) -> Self {
        Download::InvalidStatusCode(error)
    }
}