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
use std::fmt::Display;

use serde::{Serialize, Serializer};

#[derive(Debug)]
pub enum Error {
    Request(reqwest::Error),
    Parse(String),
    InvalidStop,
    NoBuses,
    ServerError,
}

impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Error::Request(req), Error::Request(other_req)) => req.to_string() == other_req.to_string(),
            (Error::Request(_), _) => false,
            (_, Error::Request(_)) => false,
            (Error::Parse(s1), Error::Parse(s2)) => s1 == s2,
            (Error::NoBuses, Error::NoBuses) => true,
            (Error::InvalidStop, Error::InvalidStop) => true,
            (Error::ServerError, Error::ServerError) => true,
            _ => false
        }
    }
}

impl Serialize for Error {
    fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
        S: Serializer {
        match self {
            Error::Request(req) => serializer.serialize_str(&req.to_string()),
            Error::Parse(string) => serializer.serialize_str(string),
            Error::NoBuses => serializer.serialize_str("NO_BUSES_FOUND"),
            Error::InvalidStop => serializer.serialize_str("INVALID_STOP_CODE"),
            Error::ServerError => serializer.serialize_str("SERVER_ERROR"),
        }
    }
}

impl From<String> for Error {
    fn from(error: String) -> Self {
        Error::Parse(error)
    }
}

impl From<reqwest::Error> for Error {
    fn from(error: reqwest::Error) -> Self {
        Error::Request(error)
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
        match *self {
            Error::Request(ref inner) => ::std::fmt::Display::fmt(inner, f),
            Error::Parse(ref inner) => ::std::fmt::Display::fmt(inner, f),
            Error::NoBuses => ::std::fmt::Display::fmt("NoBuses", f),
            Error::InvalidStop => ::std::fmt::Display::fmt("InvalidStop", f),
            Error::ServerError => ::std::fmt::Display::fmt("ServerError", f),
        }
    }
}

impl std::error::Error for Error {}