1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
use std::{error, fmt};
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use serde::de::DeserializeOwned;
pub trait Aggregate: Default + Serialize + DeserializeOwned + Sync + Send {
fn aggregate_type() -> &'static str;
}
#[derive(Debug, PartialEq)]
pub enum AggregateError {
UserError(UserErrorPayload),
TechnicalError(String),
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct UserErrorPayload {
pub code: Option<String>,
pub message: Option<String>,
pub params: Option<HashMap<String, String>>,
}
impl error::Error for AggregateError {}
impl fmt::Display for AggregateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AggregateError::TechnicalError(message) => {
write!(f, "{}", message)
}
AggregateError::UserError(message) => {
write!(f, "{}", message)
}
}
}
}
impl fmt::Display for UserErrorPayload {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "UserError - code: {:?}\n message: {:?}\n params: {:?}", &self.code, &self.message, &self.params)
}
}
impl AggregateError {
pub fn new(msg: &str) -> Self {
AggregateError::UserError(UserErrorPayload {
code: None,
message: Some(msg.to_string()),
params: None,
})
}
}
impl From<serde_json::error::Error> for AggregateError {
fn from(err: serde_json::error::Error) -> Self {
match err.classify() {
serde_json::error::Category::Syntax => AggregateError::new("invalid json"),
serde_json::error::Category::Io |
serde_json::error::Category::Data |
serde_json::error::Category::Eof => AggregateError::new("fail"),
}
}
}