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
use mio;

use open_protocol::Error as ProtocolError;

use serde_json;
use std::convert::From;
use std::error::Error as StdError;
use std::fmt;
use std::io;
use std::result::Result as StdResult;
use std::time::SystemTimeError;

pub type Result<T> = StdResult<T, Error>;

#[derive(Debug)]
pub enum Error {
    Encode,
    Decode,
    Session,
    Json(serde_json::Error),
    Transport(String),
    Protocol(ProtocolError),
    Time(SystemTimeError),
    EventLoop(String),
    Http(String),
}

impl Error {
    pub fn task<S: Into<String>>(msg: S) -> Error {
        Error::Protocol(ProtocolError::Task(msg.into()))
    }

    pub fn io(err: io::Error) -> Error {
        Error::Protocol(ProtocolError::Io(err))
    }

    pub fn http<S: Into<String>>(msg: S) -> Error {
        Error::Http(msg.into())
    }
}

impl<'a> From<&'a str> for Error {
    fn from(err: &'a str) -> Self {
        Error::task(err)
    }
}

impl From<mio::timer::TimerError> for Error {
    fn from(err: mio::timer::TimerError) -> Self {
        Error::EventLoop(err.description().to_string())
    }
}

impl From<SystemTimeError> for Error {
    fn from(err: SystemTimeError) -> Self {
        Error::Time(err)
    }
}

impl From<serde_json::Error> for Error {
    fn from(err: serde_json::Error) -> Self {
        Error::Json(err)
    }
}

impl From<ProtocolError> for Error {
    fn from(err: ProtocolError) -> Self {
        Error::Protocol(err)
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Self {
        Error::io(err)
    }
}

impl StdError for Error {
    fn description(&self) -> &str {
        match *self {
            Error::Encode => "Encode Error",
            Error::Decode => "Decode Error",
            Error::Session => "No usable session",
            Error::Json(ref e) => e.description(),
            Error::Protocol(ref e) => e.description(),
            Error::Time(ref e) => e.description(),
            Error::Transport(ref e) => e,
            Error::EventLoop(ref s) => s,
            Error::Http(ref s) => s,
        }
    }
}

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