rust_tdlib/
errors.rs

1use std::{error, fmt, io};
2
3pub type TDLibError = crate::types::Error;
4
5#[derive(Debug)]
6pub enum Error {
7    Io(io::Error),
8    SerdeJson(serde_json::Error),
9    TDLibError(TDLibError),
10    Internal(&'static str),
11    BadRequest(&'static str),
12}
13
14#[deprecated]
15pub type RTDError = Error;
16
17pub type Result<T, E = Error> = std::result::Result<T, E>;
18
19#[deprecated]
20pub type RTDResult<T, E = Error> = Result<T, E>;
21
22impl fmt::Display for Error {
23    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
24        match self {
25            Error::Io(err) => {
26                write!(f, "{}", err)
27            }
28            Error::SerdeJson(err) => {
29                write!(f, "{}", err)
30            }
31            Error::TDLibError(err) => {
32                write!(f, "{:?}", err)
33            }
34            Error::Internal(err) => {
35                write!(f, "{}", err)
36            }
37            Error::BadRequest(err) => {
38                write!(f, "{}", err)
39            }
40        }
41    }
42}
43
44impl error::Error for Error {
45    fn cause(&self) -> Option<&dyn error::Error> {
46        match self {
47            Error::Io(ref err) => Some(err),
48            Error::SerdeJson(ref err) => Some(err),
49            Error::Internal(_) => None,
50            Error::TDLibError(_) => None,
51            Error::BadRequest(_) => None,
52        }
53    }
54}
55
56impl From<io::Error> for Error {
57    fn from(err: io::Error) -> Error {
58        Error::Io(err)
59    }
60}
61
62impl From<serde_json::Error> for Error {
63    fn from(err: serde_json::Error) -> Error {
64        Error::SerdeJson(err)
65    }
66}
67
68const CLOSED_CHANNEL_ERROR: Error = Error::Internal("channel closed");
69const SEND_TO_CHANNEL_TIMEOUT: Error = Error::Internal("timeout for mpsc occurred");
70
71#[cfg(feature = "client")]
72impl<T> From<tokio::sync::mpsc::error::SendTimeoutError<T>> for Error {
73    fn from(err: tokio::sync::mpsc::error::SendTimeoutError<T>) -> Self {
74        match err {
75            tokio::sync::mpsc::error::SendTimeoutError::Timeout(_) => SEND_TO_CHANNEL_TIMEOUT,
76            tokio::sync::mpsc::error::SendTimeoutError::Closed(_) => CLOSED_CHANNEL_ERROR,
77        }
78    }
79}