Skip to main content

telegram_client/
errors.rs

1use std::any::Any;
2use std::fmt::Debug;
3use std::{error, fmt};
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 {
59    self.key
60  }
61  pub fn message(&self) -> &Option<String> {
62    &self.message
63  }
64  pub fn data(&self) -> &Option<Box<dyn TGDatable>> {
65    &self.data
66  }
67  pub fn context(&self) -> &Option<Box<dyn std::error::Error>> {
68    &self.context
69  }
70}
71
72impl fmt::Display for TGError {
73  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74    write!(
75      f,
76      "[{}]: {}",
77      self.key,
78      self.message.as_deref().unwrap_or("")
79    )
80  }
81}
82
83impl error::Error for TGError {
84  fn source(&self) -> Option<&(dyn error::Error + 'static)> {
85    self.context.as_deref()
86  }
87}
88
89impl From<RTDError> for TGError {
90  fn from(err: RTDError) -> Self {
91    let mut tgerr = Self::new("RTDLIB_ERROR");
92    tgerr.set_message(err.to_string());
93    tgerr.set_context(Box::new(err));
94    tgerr
95  }
96}
97
98#[cfg(test)]
99mod tests {
100  use super::*;
101
102  #[test]
103  fn display_includes_key_and_message() {
104    let mut err = TGError::new("CUSTOM");
105    err.set_message("boom");
106    assert_eq!(err.to_string(), "[CUSTOM]: boom");
107  }
108
109  #[test]
110  fn display_without_message_is_key_only() {
111    let err = TGError::new("CUSTOM");
112    assert_eq!(err.to_string(), "[CUSTOM]: ");
113  }
114}