Skip to main content

ferogram_connect/
error.rs

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