summaryrefslogtreecommitdiffstats
path: root/src/error.rs
blob: f7796b8cb996f7c6c28d834eed8145988a817732 (plain) (blame)
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
#[derive(Debug)]
pub enum TdlibSysError {
    LogLevelOutOfBounds(u16),
    Nul(usize),
    UtfDecode,
    CannotSetLogFile,
}

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

impl std::convert::From<std::ffi::NulError> for TdlibSysError {
    fn from(nul_err: std::ffi::NulError) -> Self {
        Self::Nul(nul_err.nul_position())
    }
}

impl std::fmt::Display for TdlibSysError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use TdlibSysError::*;
        match self {
            LogLevelOutOfBounds(lvl) => {
                write!(f, "Log level should be less than 1024. Found {}", lvl)
            }
            Nul(pos) => write!(f, "String contains nul byte at pos: {}", pos),
            UtfDecode => write!(f, "String is not utf8 encoded"),
            CannotSetLogFile => write!(f, "Could not set log file"),
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum TgError {
    /// Something went wrong, when (de)serializing shit
    #[error("Something went wrong, when (de)serializing shit: {}", .0)]
    Serde(#[from] serde_json::Error),

    /// tdlib-sys error
    #[error("tdlib-sys error: {}", .0)]
    TdSys(#[from] TdlibSysError),

    #[error("@type must not be in your structure used as Request")]
    HasTypeInJson,

    #[error("@type must be string in JsonValue used as Request")]
    HasNoTypeInJson,

    #[error("json is invalid: {}", .0)]
    InvalidJson(String),

    #[error("core channel has been closed unexpectedly")]
    ChannelClosed,

    #[error("telegram replied with error code: {code} and message: {msg}")]
    TelegramError { code: i32, msg: String },
}

impl<T> std::convert::From<crossbeam::channel::SendError<T>> for TgError {
    fn from(_: crossbeam::channel::SendError<T>) -> Self {
        Self::ChannelClosed
    }
}

pub type Error = TgError;
pub type Result<T> = std::result::Result<T, Error>;