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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! An error that should be returned from an Http API handler
//!
//! # Things to know
//!
//! `ApiError` can be converted to a `HttpApiProblem`
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::io;

use std::error::Error;

use serde::Serialize;
use serde_json::Value;

use super::*;

pub struct ApiErrorBuilder {
    /// A message that describes the error in a human readable form.
    ///
    /// In an `HttpApiProblem` this becomes the `detail` in most cases.
    ///
    /// If None:
    ///
    /// * If there is a cause, this will become the details
    /// * Otherwise there will be no details
    pub message: Option<String>,
    /// The suggested status code for the server to be returned to the client
    ///
    /// Defaults to 500.
    pub status: StatusCode,
    /// A URL that points to a detailed description of the error. If not
    /// set it will most probably become `httpstatus.es.com/XXX` when
    /// the problem response is generated.
    pub type_url: Option<String>,
    /// Additional JSON encodable information. It is up to the server how and if
    /// it adds the given information.
    pub fields: HashMap<String, Value>,
    /// This is an optional title which can be used to create a valuable output
    /// for consumers.
    pub title: Option<String>,

    pub source: Option<Box<dyn Error + Send + Sync + 'static>>,
}

impl Default for ApiErrorBuilder {
    fn default() -> Self {
        ApiErrorBuilder {
            message: None,
            status: StatusCode::INTERNAL_SERVER_ERROR,
            type_url: None,
            fields: HashMap::default(),
            title: None,
            source: None,
        }
    }
}

impl ApiErrorBuilder {
    pub fn status<S: Into<StatusCode>>(mut self, status: S) -> Self {
        self.status = status.into();
        self
    }

    pub fn title<T: Into<String>>(mut self, title: T) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn message<M: Into<String>>(mut self, message: M) -> Self {
        self.message = Some(message.into());
        self
    }

    pub fn type_url<U: Into<String>>(mut self, type_url: U) -> Self {
        self.type_url = Some(type_url.into());
        self
    }

    /// Adds a serializable field. If the serialization fails nothing will be
    /// added.
    ///
    /// An already present field with the same name will be replaced.
    pub fn field<T: Into<String>, V: Serialize>(mut self, name: T, value: V) -> Self {
        if let Ok(value) = serde_json::to_value(value) {
            self.fields.insert(name.into(), value);
        }

        self
    }

    pub fn source<E: Error + Send + Sync + 'static>(mut self, cause: E) -> Self {
        self.source = Some(Box::new(cause));
        self
    }

    pub fn finish(self) -> ApiError {
        ApiError {
            status: self.status,
            message: self.message,
            type_url: self.type_url,
            fields: self.fields,
            title: self.title,
            cause: self.source,
        }
    }
}

/// An error that should be returned from an API handler of a web service.
///
/// This should be returned from a handler instead of a premature response
/// or `HttpApiProblem`. This gives the server a chance for better introspection
/// on handler errors and also a chance to create a customized response by himself
///
/// `ApiError` requires the feature "api-error" to be enabled.
#[derive(Debug)]
pub struct ApiError {
    /// A message that describes the error in a human readable form.
    ///
    /// In an `HttpApiProblem` this becomes the `detail` in most cases.
    ///
    /// If None:
    ///
    /// * If there is a cause, this will become the details
    /// * Otherwise there will be no details
    pub message: Option<String>,
    /// The suggested status code for the server to be returned to the client
    pub status: StatusCode,
    /// A URL that points to a detailed description of the error. If not
    /// set it will most probably become `httpstatus.es.com/XXX` when
    /// the problem response is generated.
    pub type_url: Option<String>,
    /// Additional JSON encodable information. It is up to the server how and if
    /// it adds the given information.
    pub fields: HashMap<String, Value>,
    /// This is an optional title which can be used to create a valuable output
    /// for consumers.
    pub title: Option<String>,

    cause: Option<Box<dyn Error + Send + Sync + 'static>>,
}

impl ApiError {
    pub fn builder() -> ApiErrorBuilder {
        ApiErrorBuilder::default()
    }

    pub fn new<S>(status: S) -> Self
    where
        S: Into<StatusCode>,
    {
        Self {
            status: status.into(),
            message: None,
            type_url: None,
            fields: HashMap::new(),
            title: None,
            cause: None,
        }
    }

    pub fn with_message<S, M>(status: S, message: M) -> Self
    where
        M: Into<String>,
        S: Into<StatusCode>,
    {
        Self {
            status: status.into(),
            message: Some(message.into()),
            type_url: None,
            fields: HashMap::new(),
            title: None,
            cause: None,
        }
    }

    pub fn display_message(&self) -> Cow<str> {
        if let Some(message) = self.detail_message() {
            return message;
        }

        if let Some(canonical_reason) = self.status.canonical_reason() {
            return Cow::Borrowed(canonical_reason);
        }

        Cow::Borrowed(self.status.as_str())
    }

    /// Adds a serializable field. If the serialization fails nothing will be
    /// added. This method returns `true` if the field was added and `false` if
    /// the field could not be added.
    ///
    /// An already present field with the same name will be replaced.
    pub fn add_field<T: Into<String>, V: Serialize>(&mut self, name: T, value: V) -> bool {
        self.try_add_field(name, value).is_ok()
    }

    pub fn to_http_api_problem(&self) -> HttpApiProblem {
        let mut problem = HttpApiProblem::with_title_and_type_from_status(self.status);

        if let Some(detail_message) = self.detail_message() {
            problem.detail = Some(detail_message.to_string())
        }

        if let Some(custom_type_url) = self.type_url.as_ref() {
            problem.type_url = Some(custom_type_url.to_string())
        }

        if self.status != StatusCode::UNAUTHORIZED {
            for (key, value) in self.fields.iter() {
                let _ = problem.set_value(key.to_string(), value);
            }
        }

        if let Some(title) = self.title.as_ref() {
            problem.title = title.to_owned();
        }

        problem
    }

    pub fn into_http_api_problem(self) -> HttpApiProblem {
        let mut problem = HttpApiProblem::with_title_and_type_from_status(self.status);

        if let Some(detail_message) = self.detail_message() {
            problem.detail = Some(detail_message.to_string())
        }

        if let Some(custom_type_url) = self.type_url {
            problem.type_url = Some(custom_type_url)
        }

        if self.status != StatusCode::UNAUTHORIZED {
            for (key, value) in self.fields.into_iter() {
                let _ = problem.set_value(key, &value);
            }
        }

        if let Some(title) = self.title {
            problem.title = title;
        }

        problem
    }

    fn detail_message(&self) -> Option<Cow<str>> {
        if let Some(message) = self.message.as_ref() {
            return Some(Cow::Borrowed(message));
        }

        if let Some(cause) = self.source() {
            return Some(Cow::Owned(cause.to_string()));
        }

        None
    }

    #[cfg(feature = "hyper")]
    pub fn into_hyper_response(self) -> hyper::Response<hyper::Body> {
        let problem = self.into_http_api_problem();
        problem.to_hyper_response()
    }

    #[cfg(feature = "actix-web")]
    pub fn into_actix_web_response(self) -> actix_web::HttpResponse {
        let problem = self.into_http_api_problem();
        problem.into()
    }

    #[cfg(feature = "salvo")]
    pub fn into_salvo_response(self) -> salvo::Response {
        let problem = self.into_http_api_problem();
        problem.to_salvo_response()
    }
}

impl ApiError {
    pub fn with_cause<S, E>(status: S, err: E) -> Self
    where
        S: Into<StatusCode>,
        E: Error + Send + Sync + 'static,
    {
        Self {
            status: status.into(),
            message: None,
            type_url: None,
            fields: HashMap::new(),
            title: None,
            cause: Some(Box::new(err)),
        }
    }

    pub fn with_message_and_cause<S, M, E>(status: S, message: M, err: E) -> Self
    where
        S: Into<StatusCode>,
        M: Into<String>,
        E: Error + Send + Sync + 'static,
    {
        Self {
            status: status.into(),
            message: Some(message.into()),
            type_url: None,
            fields: HashMap::new(),
            title: None,
            cause: Some(Box::new(err)),
        }
    }

    pub fn set_cause<E: Error + Send + Sync + 'static>(&mut self, cause: E) {
        self.cause = Some(Box::new(cause))
    }

    /// Adds a serializable field. If the serialization fails nothing will be
    /// added. This fails if a failure occurred while adding the field.
    ///
    /// An already present field with the same name will be replaced.
    pub fn try_add_field<T: Into<String>, V: Serialize>(
        &mut self,
        name: T,
        value: V,
    ) -> Result<(), Box<dyn Error + 'static>> {
        match serde_json::to_value(value) {
            Ok(value) => {
                self.fields.insert(name.into(), value);
                Ok(())
            }
            Err(err) => Err(Box::new(err)),
        }
    }
}

impl Error for ApiError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.cause.as_ref().map(|e| &**e as _)
    }
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(detail_message) = self.detail_message() {
            write!(f, "{}: {}", self.status, detail_message)
        } else {
            write!(f, "{}", self.status)
        }
    }
}

impl From<StatusCode> for ApiError {
    fn from(s: StatusCode) -> Self {
        Self::new(s)
    }
}

impl From<ApiError> for HttpApiProblem {
    fn from(error: ApiError) -> Self {
        error.into_http_api_problem()
    }
}

impl From<io::Error> for ApiError {
    fn from(error: io::Error) -> Self {
        ApiError::with_message_and_cause(
            StatusCode::INTERNAL_SERVER_ERROR,
            "An internal IO error occurred",
            error,
        )
    }
}

#[cfg(feature = "hyper")]
impl From<hyper::Error> for ApiError {
    fn from(error: hyper::Error) -> Self {
        ApiError::with_message_and_cause(
            StatusCode::INTERNAL_SERVER_ERROR,
            "An internal error caused by hyper occurred",
            error,
        )
    }
}

#[cfg(feature = "hyper")]
impl From<ApiError> for hyper::Response<hyper::Body> {
    fn from(error: ApiError) -> hyper::Response<hyper::Body> {
        error.into_hyper_response()
    }
}

#[cfg(feature = "actix-web")]
impl From<actix::prelude::MailboxError> for ApiError {
    fn from(error: actix::prelude::MailboxError) -> Self {
        ApiError::with_message_and_cause(
            StatusCode::INTERNAL_SERVER_ERROR,
            "An internal error caused by internal messaging occured",
            error,
        )
    }
}

#[cfg(feature = "actix-web")]
impl From<ApiError> for actix_web::HttpResponse {
    fn from(error: ApiError) -> Self {
        error.into_actix_web_response()
    }
}

#[cfg(feature = "actix-web")]
impl actix_web::error::ResponseError for ApiError {
    fn error_response(&self) -> actix_web::HttpResponse {
        let json = self.to_http_api_problem().json_bytes();
        let actix_status = actix_web::http::StatusCode::from_u16(self.status.as_u16())
            .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);

        actix_web::HttpResponse::build(actix_status)
            .header(
                actix_web::http::header::CONTENT_TYPE,
                PROBLEM_JSON_MEDIA_TYPE,
            )
            .body(json)
    }
}

#[cfg(feature = "warp")]
impl warp::reject::Reject for ApiError {}

#[cfg(feature = "salvo")]
impl From<salvo::Error> for ApiError {
    fn from(error: salvo::Error) -> Self {
        ApiError::with_message_and_cause(
            StatusCode::INTERNAL_SERVER_ERROR,
            "An internal error caused by salvo occurred",
            error,
        )
    }
}

#[cfg(feature = "salvo")]
impl From<ApiError> for salvo::Response {
    fn from(error: ApiError) -> salvo::Response {
        error.into_salvo_response()
    }
}