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
use std::{error, fmt, num::ParseIntError};

use async_native_tls::Error as TlsError;
use tokio::{io::Error as IoError, time::error::Elapsed as TimeoutError};

#[derive(Debug)]
pub enum ErrorKind {
    Tls(TlsError),
    Io(IoError),
    Timeout(TimeoutError),
    ParseInt(ParseIntError),
    Connect,
    NotConnected,
    ShouldNotBeConnected,
    IncorrectStateForCommand,
    MessageIsDeleted,
    FeatureUnsupported,
    ServerFailedToGreet,
    ParseServerAddress,
    SecureConnection,
    SendCommand,
    InvalidResponse,
    NoResponse,
    ServerError,
}

#[derive(Debug)]
pub struct Error {
    message: String,
    kind: ErrorKind,
}

impl Error {
    pub fn new<S>(error_kind: ErrorKind, message: S) -> Self
    where
        String: From<S>,
    {
        Self {
            message: message.into(),
            kind: error_kind,
        }
    }

    pub fn message(&self) -> &str {
        &self.message
    }

    pub fn kind(&self) -> &ErrorKind {
        &self.kind
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        &self.message
    }

    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self.kind() {
            _ => None,
        }
    }
}

impl Into<String> for Error {
    fn into(self) -> String {
        self.message
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl From<TlsError> for Error {
    fn from(tls_error: async_native_tls::Error) -> Self {
        Self::new(
            ErrorKind::Tls(tls_error),
            "Error creating secure connection",
        )
    }
}

impl From<IoError> for Error {
    fn from(io_error: IoError) -> Self {
        Self::new(ErrorKind::Io(io_error), "Error with connection to server")
    }
}

impl From<ParseIntError> for Error {
    fn from(parse_int_error: ParseIntError) -> Self {
        Self::new(ErrorKind::ParseInt(parse_int_error), "Failed to parse int")
    }
}

impl From<TimeoutError> for Error {
    fn from(timeout_error: TimeoutError) -> Self {
        Self::new(
            ErrorKind::Timeout(timeout_error),
            "Timeout when connecting to server",
        )
    }
}