Skip to main content

ferogram_connect/
error.rs

1// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
2//
3// ferogram: async Telegram MTProto client in Rust
4// https://github.com/ankit-chaubey/ferogram
5//
6// Licensed under either the MIT License or the Apache License 2.0.
7// See the LICENSE-MIT or LICENSE-APACHE file in this repository:
8// https://github.com/ankit-chaubey/ferogram
9//
10// Feel free to use, modify, and share this code.
11// Please keep this notice when redistributing.
12
13use std::{fmt, io};
14
15/// Errors produced by [`Connection`](crate::Connection) and transport helpers.
16#[derive(Debug)]
17pub enum ConnectError {
18    /// Network / I/O failure.
19    Io(io::Error),
20    /// Protocol violation or decoding failure.
21    Other(String),
22    /// Telegram transport-level error code (negative 4-byte word).
23    TransportCode(i32),
24    /// RPC error returned by Telegram (code + message string).
25    Rpc { code: i32, message: String },
26}
27
28impl ConnectError {
29    /// Build the `Other` variant from any string-like value.
30    pub fn other(msg: impl Into<String>) -> Self {
31        Self::Other(msg.into())
32    }
33}
34
35impl fmt::Display for ConnectError {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            Self::Io(e) => write!(f, "I/O error: {e}"),
39            Self::Other(s) => write!(f, "connect error: {s}"),
40            Self::TransportCode(c) => write!(f, "Telegram transport error: {c}"),
41            Self::Rpc { code, message } => write!(f, "RPC {code}: {message}"),
42        }
43    }
44}
45
46impl std::error::Error for ConnectError {
47    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
48        match self {
49            Self::Io(e) => Some(e),
50            _ => None,
51        }
52    }
53}
54
55impl From<io::Error> for ConnectError {
56    fn from(e: io::Error) -> Self {
57        Self::Io(e)
58    }
59}
60
61impl From<ferogram_tl_types::deserialize::Error> for ConnectError {
62    fn from(e: ferogram_tl_types::deserialize::Error) -> Self {
63        Self::Other(format!("TL deserialize error: {e:?}"))
64    }
65}