mmtickets_common/middlewares/
error_handler.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
use axum::response::IntoResponse;
use hyper::StatusCode;
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
struct InnerErrorMessage(String);

#[derive(Debug, Deserialize, Serialize)]
pub struct InnerError {
    errors: Vec<InnerErrorMessage>,
}

impl InnerError {
    pub fn new(message: String) -> Self {
        Self {
            errors: vec![InnerErrorMessage(message)],
        }
    }

    pub fn add(&mut self, message: String) {
        self.errors.push(InnerErrorMessage(message));
    }
}

impl ToString for InnerError {
    fn to_string(&self) -> String {
        serde_json::to_string(&self).unwrap()
    }
}

pub struct CommonError {
    pub status: StatusCode,
    pub message: InnerError,
}

impl CommonError {
    pub fn new(status: StatusCode, message: String) -> Self {
        Self {
            status,
            message: InnerError::new(message),
        }
    }

    pub fn add(&mut self, message: String) {
        self.message.add(message);
    }
}

impl IntoResponse for CommonError {
    fn into_response(self) -> axum::response::Response {
        (self.status, self.message.to_string()).into_response()
    }
}

impl std::fmt::Debug for CommonError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "CommonError {{ status: {:?}, message: {:?} }}",
            self.status, self.message
        )
    }
}

impl std::fmt::Display for CommonError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "CommonError {{ status: {:?}, message: {:?} }}",
            self.status, self.message
        )
    }
}