telegram_client/
errors.rs1use std::{error, fmt};
2use std::any::Any;
3use std::fmt::Debug;
4
5use rtdlib::errors::RTDError;
6
7pub trait TGDatable: Debug {
8 fn as_any(&self) -> &dyn Any;
9}
10
11#[derive(Debug)]
12pub struct TGError {
13 key: &'static str,
14 message: Option<String>,
15 data: Option<Box<dyn TGDatable>>,
16 context: Option<Box<dyn std::error::Error>>
17}
18
19pub type TGResult<T> = Result<T, TGError>;
20
21impl TGError {
22 pub fn new(key: &'static str) -> Self {
23 Self {
24 key,
25 message: None,
26 data: None,
27 context: None
28 }
29 }
30 pub fn custom(message: impl AsRef<str>) -> Self {
31 let mut error = Self::new("CUSTOM_ERROR");
32 error.set_message(message.as_ref());
33 error
34 }
35}
36
37impl TGError {
38 pub fn set_key(&mut self, key: &'static str) -> &mut Self {
39 self.key = key;
40 self
41 }
42
43 pub fn set_message(&mut self, message: impl AsRef<str>) -> &mut Self {
44 self.message = Some(message.as_ref().to_string());
45 self
46 }
47
48 pub fn set_data(&mut self, data: Box<dyn TGDatable>) -> &mut Self {
49 self.data = Some(data);
50 self
51 }
52
53 pub fn set_context(&mut self, context: Box<dyn std::error::Error>) -> &mut Self {
54 self.context = Some(context);
55 self
56 }
57
58 pub fn key(&self) -> &'static str { self.key }
59 pub fn message(&self) -> &Option<String> { &self.message }
60 pub fn data(&self) -> &Option<Box<dyn TGDatable>> { &self.data }
61 pub fn context(&self) -> &Option<Box<dyn std::error::Error>> { &self.context }
62}
63
64
65impl fmt::Display for TGError {
66 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
67 write!(f, "[{}]: {}", self.key, self.message.clone().map_or("".to_string(), |v| v))
68 }
69}
70
71impl error::Error for TGError {
72 fn cause(&self) -> Option<&dyn error::Error> {
73 None
74 }
75}
76
77impl From<RTDError> for TGError {
78 fn from(err: RTDError) -> Self {
79 let mut tgerr = Self::new("RTDLIB_ERROR");
80 tgerr.set_message(err.to_string());
81 tgerr.set_context(Box::new(err));
82 tgerr
83 }
84}
85