graphql_starter/error/
api.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
use std::collections::HashMap;

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
};
use http::{header::IntoHeaderName, HeaderMap, HeaderValue};
use serde::Serialize;

use super::Error;
use crate::axum::extract::Json;

pub type ApiResult<T, E = Box<ApiError>> = std::result::Result<T, E>;

/// An RFC-7807 compatible error implementing axum's [IntoResponse]
#[derive(Debug, Serialize)]
pub struct ApiError {
    /// A short, human-readable title for the general error type
    title: String,
    /// Conveying the HTTP status code
    #[serde(serialize_with = "serialize_status_u16")]
    status: StatusCode,
    /// A human-readable description of the specific error
    detail: String,
    /// Additional information about the error
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    info: HashMap<String, String>,
    /// Additional details for each one of the errors encountered
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    errors: HashMap<String, serde_json::Value>,
    /// Additional headers to be sent with the response
    #[serde(skip)]
    headers: Option<HeaderMap>,
}

impl ApiError {
    /// Builds a new error from the detail message
    pub fn new(status: StatusCode, detail: impl Into<String>) -> Self {
        ApiError {
            title: status.canonical_reason().unwrap_or("Internal server error").to_owned(),
            status,
            detail: detail.into(),
            info: Default::default(),
            errors: Default::default(),
            headers: None,
        }
    }

    /// Modify the title
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Extend the error with additional information
    pub fn with_info(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.info.insert(key.into(), value.into());
        self
    }

    /// Extend the error with additional information about errors
    pub fn with_error_info(mut self, field: impl Into<String>, info: serde_json::Value) -> Self {
        self.errors.insert(field.into(), info);
        self
    }

    /// Extend the error with an additional header
    pub fn with_header(mut self, key: impl IntoHeaderName, value: impl TryInto<HeaderValue>) -> Self {
        if let Ok(value) = value.try_into() {
            let headers = self.headers.get_or_insert_with(Default::default);
            headers.append(key, value);
        }
        self
    }

    /// Boxes this error
    pub fn boxed(self) -> Box<Self> {
        Box::new(self)
    }

    /// Retrieves the error title
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Retrieves the status code
    pub fn status(&self) -> StatusCode {
        self.status
    }

    /// Retrieves the error detail
    pub fn detail(&self) -> &str {
        &self.detail
    }

    /// Retrieves the error info
    pub fn info(&self) -> &HashMap<String, String> {
        &self.info
    }

    /// Retrieves the internal errors
    pub fn errors(&self) -> &HashMap<String, serde_json::Value> {
        &self.errors
    }

    /// Retrieves the additional headers
    pub fn headers(&self) -> &Option<HeaderMap> {
        &self.headers
    }
}

impl From<Box<Error>> for ApiError {
    fn from(err: Box<Error>) -> Self {
        (*err).into()
    }
}
impl From<Box<Error>> for Box<ApiError> {
    fn from(err: Box<Error>) -> Self {
        (*err).into()
    }
}

impl<T> From<T> for Box<ApiError>
where
    T: Into<Error>,
{
    fn from(error: T) -> Self {
        ApiError::from(error).boxed()
    }
}

impl<T> From<T> for ApiError
where
    T: Into<Error>,
{
    fn from(error: T) -> Self {
        let error: Error = error.into();

        // Trace error before losing context information, this should usually happen just before returning to clients
        if error.unexpected {
            tracing::error!("{error:#}");
        } else if tracing::event_enabled!(tracing::Level::DEBUG) {
            tracing::warn!("{error:#}")
        } else {
            tracing::warn!("{error}")
        }

        // Build the ApiError
        let mut ret = ApiError::new(error.info.status(), error.info.message());

        // Extend the error info to allow for i18n
        ret = ret.with_info("errorCode", error.info.code());
        ret = ret.with_info("rawMessage", error.info.raw_message());
        for (key, value) in error.info.fields() {
            ret = ret.with_info(key, value);
        }

        // Extend with the error properties
        if let Some(properties) = error.properties {
            for (key, value) in properties {
                ret = ret.with_error_info(key, value);
            }
        }

        ret
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        if let Some(headers) = &self.headers {
            (self.status, headers.clone(), Json(self)).into_response()
        } else {
            (self.status, Json(self)).into_response()
        }
    }
}
impl IntoResponse for Box<ApiError> {
    fn into_response(self) -> Response {
        (*self).into_response()
    }
}

fn serialize_status_u16<S>(status: &StatusCode, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_u16(status.as_u16())
}