telegram_bot2/
error.rs

1use log::error;
2use serde::de::DeserializeOwned;
3use serde::{Deserialize, Serialize};
4
5/// Any error that may occur when sending a request to Telegram's API
6#[derive(Debug)]
7pub enum Error {
8    /// Error while parsing the query result. This error should never occur, if it does, please open a issue on the [repo]("https://www.gitlab.com/Thechi2000/telegram-api-rut/issues)
9    ParseError(serde_json::Error),
10    /// Error while reading files to upload
11    IOError(std::io::Error),
12    /// Error while communicating with the Telegram server
13    RequestError(reqwest::Error),
14    /// Error returned by the API
15    TelegramError(TelegramError),
16}
17
18#[derive(Serialize, Deserialize, Debug)]
19#[serde(untagged)]
20enum Response<A> {
21    Ok { ok: bool, result: A },
22
23    Error { ok: bool, error_code: u32, description: String },
24}
25
26/// Describe an error returned by the API
27#[derive(Serialize, Deserialize, Debug)]
28pub struct TelegramError {
29    /// Whether the request was successful (always false) TODO remove
30    ok: bool,
31    error_code: u32,
32    description: String,
33}
34
35impl From<serde_json::Error> for Error {
36    fn from(e: serde_json::Error) -> Self {
37        Error::ParseError(e)
38    }
39}
40
41impl From<reqwest::Error> for Error {
42    fn from(e: reqwest::Error) -> Self {
43        Error::RequestError(e)
44    }
45}
46
47impl From<TelegramError> for Error {
48    fn from(e: TelegramError) -> Self {
49        Error::TelegramError(e)
50    }
51}
52
53impl From<std::io::Error> for Error {
54    fn from(e: std::io::Error) -> Self {
55        Error::IOError(e)
56    }
57}
58
59pub(crate) fn parse_api_result<A: DeserializeOwned>(text: String) -> Result<A, Error> {
60    #[derive(Deserialize)]
61    struct O<B> {
62        ok: bool,
63        result: B,
64    }
65
66    match serde_json::from_str::<Response<A>>(text.as_str()).map_err(|e| {
67        error!("Could not parse telegram response. Please report this issue on https://www.github.com/Thechi2000/telegram-api-rust\nServer response: {}", text);
68        Error::ParseError(e)
69    })? {
70        Response::Ok { ok: _, result } => Ok(result),
71        Response::Error { ok, error_code, description } => Err(Error::TelegramError(TelegramError { ok, error_code, description })),
72    }
73}