-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy patherror.rs
328 lines (278 loc) · 8.36 KB
/
error.rs
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::Json;
use colored::Colorize;
use deadpool_redis::redis::RedisError;
use deadpool_redis::PoolError;
use diesel::result::Error as DieselError;
use editoast_models::db_connection_pool::DatabasePoolBuildError;
use editoast_models::db_connection_pool::DatabasePoolError;
use editoast_models::DatabaseError;
use serde::Deserialize;
use serde::Serialize;
use serde_json::{json, Value};
use std::backtrace::Backtrace;
use std::collections::HashMap;
use std::result::Result as StdResult;
use std::{
error::Error,
fmt::{Display, Formatter},
};
use tracing::error;
use utoipa::ToSchema;
use validator::{ValidationErrors, ValidationErrorsKind};
editoast_common::schemas! {
InternalError,
}
pub type Result<T, E = InternalError> = StdResult<T, E>;
/// Trait for all errors that can be returned by editoast
pub trait EditoastError: Error + Send + Sync {
fn get_status(&self) -> StatusCode;
fn get_type(&self) -> &str;
fn context(&self) -> HashMap<String, Value> {
Default::default()
}
}
#[derive(Serialize, Deserialize)]
#[serde(remote = "StatusCode")]
struct StatusCodeRemoteDef(#[serde(getter = "StatusCode::as_u16")] u16);
impl From<StatusCodeRemoteDef> for StatusCode {
fn from(def: StatusCodeRemoteDef) -> Self {
StatusCode::from_u16(def.0).unwrap()
}
}
fn default_status_code() -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
pub struct InternalError {
#[serde(with = "StatusCodeRemoteDef", default = "default_status_code")]
#[schema(value_type = u16, minimum = 100, maximum = 599)]
pub status: StatusCode,
#[serde(rename = "type")]
pub error_type: String,
pub context: HashMap<String, Value>,
pub message: String,
}
impl InternalError {
pub fn get_type(&self) -> &str {
&self.error_type
}
pub fn get_status(&self) -> StatusCode {
self.status
}
pub fn set_status(&mut self, status: StatusCode) {
self.status = status;
}
pub fn get_context(&self) -> &HashMap<String, Value> {
&self.context
}
pub fn with_context<S: AsRef<str>, V: Into<Value>>(mut self, key: S, value: V) -> Self {
self.context.insert(key.as_ref().into(), value.into());
self
}
}
impl Error for InternalError {}
impl Display for InternalError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl<T: EditoastError> From<T> for InternalError {
fn from(err: T) -> Self {
InternalError {
status: err.get_status(),
error_type: err.get_type().to_owned(),
context: err.context(),
message: err.to_string(),
}
}
}
impl IntoResponse for InternalError {
fn into_response(self) -> Response {
error!(
"[{}] {}: {}",
self.error_type.bold(),
self.message,
Backtrace::capture() // won't log unless RUST_BACKTRACE=1
);
(self.status, Json(self)).into_response()
}
}
/// Handle all diesel errors
impl EditoastError for DieselError {
fn get_status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn get_type(&self) -> &str {
"editoast:DieselError"
}
}
inventory::submit! {
crate::error::ErrorDefinition::new("editoast:DatabaseAccessError", "DatabaseAccessError", "DatabaseAccessError", 500u16, r#"{}"#)
}
impl EditoastError for DatabasePoolBuildError {
fn get_status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn get_type(&self) -> &str {
"editoast:DatabaseAccessError"
}
}
impl EditoastError for DatabasePoolError {
fn get_status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn get_type(&self) -> &str {
"editoast:DatabaseAccessError"
}
}
impl EditoastError for DatabaseError {
fn get_status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn get_type(&self) -> &str {
"editoast:DatabaseAccessError"
}
}
/// Handle all valkey errors
impl EditoastError for RedisError {
fn get_status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn get_type(&self) -> &str {
"editoast:ValkeyError"
}
}
/// Handle all valkey pool errors
impl EditoastError for PoolError {
fn get_status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn get_type(&self) -> &str {
"editoast:ValkeyPoolError"
}
}
/// Handle all json errors
impl EditoastError for ValidationErrors {
fn get_status(&self) -> StatusCode {
StatusCode::BAD_REQUEST
}
fn get_type(&self) -> &str {
"editoast:ValidationError"
}
fn context(&self) -> HashMap<String, Value> {
let mut context_map = HashMap::new();
for (field, error_kind) in self.errors() {
if let ValidationErrorsKind::Field(errors) = error_kind {
let mut name = *field;
if name == "__all__" {
name = "schema_validation";
}
let error_messages: Vec<String> =
errors.iter().map(|error| error.to_string()).collect();
context_map.insert(name.to_owned(), json!(error_messages));
}
}
context_map
}
}
/// Handle database pool errors
impl EditoastError for diesel_async::pooled_connection::deadpool::PoolError {
fn get_status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn get_type(&self) -> &str {
"editoast:DatabasePoolError"
}
}
impl EditoastError for reqwest::Error {
fn get_status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn get_type(&self) -> &str {
"editoast:ReqwestError"
}
}
impl EditoastError for serde_json::Error {
fn get_status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn get_type(&self) -> &str {
"editoast:SerdeJsonError"
}
}
impl EditoastError for json_patch::PatchError {
fn get_status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn get_type(&self) -> &str {
"editoast:JsonPatchError"
}
}
inventory::submit! {
crate::error::ErrorDefinition::new("editoast:geometry:UnexpectedGeometry", "UnexpectedGeometry", "GeometryError", 404u16, r#"{"expected":"String","actual":"String"}"#)
}
impl EditoastError for editoast_schemas::errors::GeometryError {
fn get_status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn get_type(&self) -> &str {
"editoast:geometry:UnexpectedGeometry"
}
fn context(&self) -> HashMap<String, Value> {
match self {
Self::UnexpectedGeometry { expected, actual } => {
let mut context = HashMap::new();
context.insert("expected".to_string(), json!(expected));
context.insert("actual".to_string(), json!(actual));
context
}
}
}
}
inventory::submit! {
ErrorDefinition::new("editoast:model:ModelError", "", "ModelError", 500u16, r#"{}"#)
}
impl EditoastError for editoast_models::model::Error {
fn get_status(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn get_type(&self) -> &str {
"editoast:ModelError"
}
}
// error definition : uses by the macro EditoastError to generate
// the list of error and share it with the openAPI generator
#[derive(Debug)]
pub struct ErrorDefinition {
pub id: &'static str,
pub name: &'static str,
pub namespace: &'static str,
pub status: u16,
context_serialized: &'static str,
}
impl ErrorDefinition {
pub const fn new(
id: &'static str,
name: &'static str,
namespace: &'static str,
status: u16,
context_serialized: &'static str,
) -> Self {
ErrorDefinition {
id,
name,
namespace,
status,
context_serialized,
}
}
pub fn get_context(&self) -> HashMap<String, String> {
serde_json::from_str(self.context_serialized).expect("Error context should be a valid json")
}
pub fn get_schema_name(&self) -> String {
format!("Editoast{}{}", self.namespace, self.name)
}
}
inventory::collect!(ErrorDefinition);