mini_game_service/errors/
mod.rs

1use std::{
2    error::Error,
3    fmt::{Debug, Display, Formatter},
4    ops::{Deref, DerefMut},
5};
6
7mod for_reqwest;
8
9#[derive(Clone)]
10pub struct GameError {
11    kind: Box<GameErrorKind>,
12}
13
14#[derive(Clone, Debug)]
15pub enum GameErrorKind {
16    ServiceError { external_code: i64, source: String, message: String },
17}
18
19impl From<GameErrorKind> for GameError {
20    fn from(value: GameErrorKind) -> Self {
21        GameError { kind: Box::new(value) }
22    }
23}
24
25impl Error for GameError {}
26impl Error for GameErrorKind {}
27
28impl Debug for GameError {
29    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
30        Debug::fmt(&self.kind, f)
31    }
32}
33
34impl Display for GameError {
35    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
36        Display::fmt(&self.kind, f)
37    }
38}
39
40impl Display for GameErrorKind {
41    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
42        match self {
43            GameErrorKind::ServiceError { external_code, source, message } => {
44                write!(f, "ServiceError {{ external_code: {}, source: {}, message: {} }}", external_code, source, message)
45            }
46        }
47    }
48}
49
50impl Deref for GameError {
51    type Target = GameErrorKind;
52
53    fn deref(&self) -> &Self::Target {
54        &self.kind
55    }
56}
57
58impl DerefMut for GameError {
59    fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
60        &mut self.kind
61    }
62}
63
64impl GameError {
65    pub fn service_error(source: impl Into<String>, message: impl Into<String>) -> GameError {
66        GameError {
67            kind: Box::new(GameErrorKind::ServiceError { external_code: 0, source: source.into(), message: message.into() }),
68        }
69    }
70    pub fn set_code(&mut self, code: i64) {
71        match self.deref_mut() {
72            GameErrorKind::ServiceError { external_code, .. } => {
73                *external_code = code;
74            }
75        }
76    }
77    pub fn with_code(mut self, code: i64) -> Self {
78        self.set_code(code);
79        self
80    }
81}