via/
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
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! Conviently work with errors that may occur in an application.
//!

use http::StatusCode;
use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};
use std::error::Error as StdError;
use std::fmt::{self, Debug, Display, Formatter};

use crate::response::Response;

/// A type alias for a boxed
/// [`Error`](std::error::Error)
/// that is `Send + Sync`.
///
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// An error type that can act as a specialized version of a
/// [`ResponseBuilder`](crate::response::ResponseBuilder).
///
#[derive(Debug)]
pub struct Error {
    as_json: bool,
    status: StatusCode,
    message: Option<String>,
    error: BoxError,
}

/// A serialized representation of an individual error.
///
struct SerializeError<'a> {
    message: &'a str,
}

impl Error {
    /// Returns a new [`Error`] with the provided message.
    ///
    pub fn new(source: BoxError) -> Self {
        Self::internal_server_error(source)
    }

    /// Returns a new [`Error`] that will be serialized to JSON when converted to
    /// a [`Response`].
    ///
    pub fn as_json(self) -> Self {
        Self {
            as_json: true,
            ..self
        }
    }

    /// Returns a new [`Error`] that will eagerly map the message that will be
    /// included in the body of the [`Response`] that will be generated from
    /// self by calling the provided closure. If the closure returns `None`,
    /// the message will be left unchanged.
    ///
    /// # Example
    ///
    /// ```
    /// use via::{BoxError, ErrorBoundary, Next, Request};
    ///
    /// #[tokio::main(flavor = "current_thread")]
    /// async fn main() -> Result<(), BoxError> {
    ///     let mut app = via::new(());
    ///
    ///     // Add an `ErrorBoundary` middleware to the route tree that maps
    ///     // errors that occur in subsequent middleware by calling the `redact`
    ///     // function.
    ///     app.include(ErrorBoundary::map(|error, _| {
    ///         error.redact(|message| {
    ///             if message.contains("password") {
    ///                 // If password is even mentioned in the error, return an
    ///                 // opaque message instead. You'll probably want something
    ///                 // more sophisticated than this in production.
    ///                 Some("An error occurred...".to_owned())
    ///             } else {
    ///                 // Otherwise, use the existing error message.
    ///                 None
    ///             }
    ///         })
    ///     }));
    ///
    ///     Ok(())
    /// }
    /// ```
    ///
    pub fn redact(self, f: impl FnOnce(&str) -> Option<String>) -> Self {
        match &self.message {
            Some(message) => match f(message) {
                Some(redacted) => self.with_message(redacted),
                None => self,
            },
            None => {
                let message = self.error.to_string();
                let redacted = f(&message).unwrap_or(message);

                self.with_message(redacted)
            }
        }
    }

    /// Returns a new [`Error`] that will use the provided message instead of
    /// calling the [`Display`] implementation of the error source when
    /// converted to a [`Response`].
    ///
    pub fn with_message(self, message: String) -> Self {
        Self {
            message: Some(message),
            ..self
        }
    }

    /// Sets the status code of that will be used when converted to a
    /// [`Response`].
    ///
    pub fn with_status(self, status: StatusCode) -> Self {
        // Placeholder for tracing...
        // Warn if the status code is not in the 4xx or 5xx range.
        Self { status, ..self }
    }

    /// Returns a new [`Error`] that will use the canonical reason phrase of the
    /// status code as the message included in the [`Response`] body that is
    /// generated when converted to a [`Response`].
    ///
    /// # Example
    ///
    /// ```
    /// use via::{BoxError, ErrorBoundary, Next, Request};
    ///
    /// #[tokio::main(flavor = "current_thread")]
    /// async fn main() -> Result<(), BoxError> {
    ///     let mut app = via::new(());
    ///
    ///     // Add an `ErrorBoundary` middleware to the route tree that maps
    ///     // errors that occur in subsequent middleware by calling the
    ///     // `use_canonical_reason` function.
    ///     app.include(ErrorBoundary::map(|error, _| {
    ///         // Prevent error messages that occur in downstream middleware from
    ///         // leaking into the response body by using the reason phrase of
    ///         // the status code associated with the error.
    ///         error.use_canonical_reason()
    ///     }));
    ///
    ///     Ok(())
    /// }
    /// ```
    ///
    pub fn use_canonical_reason(self) -> Self {
        if let Some(reason) = self.status.canonical_reason() {
            self.with_message(reason.to_owned())
        } else {
            // Placeholder for tracing...
            self.with_message("An error occurred".to_owned())
        }
    }

    /// Returns an iterator over the sources of this error.
    ///
    pub fn iter(&self) -> impl Iterator<Item = &dyn StdError> {
        Some(self.source()).into_iter()
    }

    /// Returns a reference to the error source.
    ///
    pub fn source(&self) -> &(dyn StdError + 'static) {
        &*self.error
    }
}

impl Error {
    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `400 Bad Request` status.
    ///
    pub fn bad_request(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::BAD_REQUEST, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `401 Unauthorized` status.
    ///
    pub fn unauthorized(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::UNAUTHORIZED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `402 Payment Required` status.
    ///
    pub fn payment_required(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::PAYMENT_REQUIRED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `403 Forbidden` status.
    ///
    pub fn forbidden(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::FORBIDDEN, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `404 Not Found` status.
    ///
    pub fn not_found(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::NOT_FOUND, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `405 Method Not Allowed` status.
    ///
    pub fn method_not_allowed(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::METHOD_NOT_ALLOWED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `406 Not Acceptable` status.
    ///
    pub fn not_acceptable(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::NOT_ACCEPTABLE, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `407 Proxy Authentication Required` status.
    ///
    pub fn proxy_authentication_required(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::PROXY_AUTHENTICATION_REQUIRED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `408 Request Timeout` status.
    ///
    pub fn request_timeout(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::REQUEST_TIMEOUT, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `409 Conflict` status.
    ///
    pub fn conflict(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::CONFLICT, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `410 Gone` status.
    ///
    pub fn gone(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::GONE, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `411 Length Required` status.
    ///
    pub fn length_required(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::LENGTH_REQUIRED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `412 Precondition Failed` status.
    ///
    pub fn precondition_failed(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::PRECONDITION_FAILED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `413 Payload Too Large` status.
    ///
    pub fn payload_too_large(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::PAYLOAD_TOO_LARGE, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `414 URI Too Long` status.
    ///
    pub fn uri_too_long(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::URI_TOO_LONG, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `415 Unsupported Media Type` status.
    ///
    pub fn unsupported_media_type(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::UNSUPPORTED_MEDIA_TYPE, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `416 Range Not Satisfiable` status.
    ///
    pub fn range_not_satisfiable(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::RANGE_NOT_SATISFIABLE, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `417 Expectation Failed` status.
    ///
    pub fn expectation_failed(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::EXPECTATION_FAILED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `418 I'm a teapot` status.
    ///
    pub fn im_a_teapot(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::IM_A_TEAPOT, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `421 Misdirected Request` status.
    ///
    pub fn misdirected_request(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::MISDIRECTED_REQUEST, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `422 Unprocessable Entity` status.
    ///
    pub fn unprocessable_entity(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::UNPROCESSABLE_ENTITY, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `423 Locked` status.
    ///
    pub fn locked(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::LOCKED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `424 Failed Dependency` status.
    ///
    pub fn failed_dependency(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::FAILED_DEPENDENCY, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `426 Upgrade Required` status.
    ///
    pub fn upgrade_required(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::UPGRADE_REQUIRED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `428 Precondition Required` status.
    ///
    pub fn precondition_required(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::PRECONDITION_REQUIRED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `429 Too Many Requests` status.
    ///
    pub fn too_many_requests(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::TOO_MANY_REQUESTS, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `431 Request Header Fields Too Large` status.
    ///
    pub fn request_header_fields_too_large(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `451 Unavailable For Legal Reasons` status.
    ///
    pub fn unavailable_for_legal_reasons(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `500 Internal Server Error` status.
    ///
    pub fn internal_server_error(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::INTERNAL_SERVER_ERROR, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `501 Not Implemented` status.
    ///
    pub fn not_implemented(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::NOT_IMPLEMENTED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `502 Bad Gateway` status.
    ///
    pub fn bad_gateway(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::BAD_GATEWAY, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `503 Service Unavailable` status.
    ///
    pub fn service_unavailable(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::SERVICE_UNAVAILABLE, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `504 Gateway Timeout` status.
    ///
    pub fn gateway_timeout(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::GATEWAY_TIMEOUT, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `505 HTTP Version Not Supported` status.
    ///
    pub fn http_version_not_supported(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::HTTP_VERSION_NOT_SUPPORTED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `506 Variant Also Negotiates` status.
    ///
    pub fn variant_also_negotiates(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::VARIANT_ALSO_NEGOTIATES, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `507 Insufficient Storage` status.
    ///
    pub fn insufficient_storage(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::INSUFFICIENT_STORAGE, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `508 Loop Detected` status.
    ///
    pub fn loop_detected(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::LOOP_DETECTED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `510 Not Extended` status.
    ///
    pub fn not_extended(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::NOT_EXTENDED, source)
    }

    /// Returns a new [`Error`] from the provided source that will generate a
    /// [`Response`] with a `511 Network Authentication Required` status.
    ///
    pub fn network_authentication_required(source: BoxError) -> Self {
        Self::new_with_status(StatusCode::NETWORK_AUTHENTICATION_REQUIRED, source)
    }
}

impl Error {
    fn new_with_status(status: StatusCode, source: BoxError) -> Self {
        Self {
            as_json: false,
            message: None,
            error: source,
            status,
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Display::fmt(&self.error, f)
    }
}

impl<T> From<T> for Error
where
    T: StdError + Send + Sync + 'static,
{
    fn from(source: T) -> Self {
        Self {
            as_json: false,
            message: None,
            status: StatusCode::INTERNAL_SERVER_ERROR,
            error: Box::new(source),
        }
    }
}

impl From<Error> for Response {
    fn from(error: Error) -> Response {
        let mut respond_with_json = error.as_json;

        loop {
            if !respond_with_json {
                let mut response = Response::new(error.to_string().into());

                *response.status_mut() = error.status;
                break response;
            }

            match Response::build().status(error.status).json(&error) {
                Ok(response) => break response,
                Err(error) => {
                    respond_with_json = false;
                    // Placeholder for tracing...
                    if cfg!(debug_assertions) {
                        eprintln!("Error: {}", error);
                    }
                }
            }
        }
    }
}

impl Serialize for Error {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("Error", 1)?;

        // Serialize the error as a single element array containing an object with
        // a message field. We do this to provide compatibility with popular API
        // specification formats like GraphQL and JSON:API.
        if let Some(message) = &self.message {
            let errors = [SerializeError { message }];
            state.serialize_field("errors", &errors)?;
        } else {
            let message = self.error.to_string();
            let errors = [SerializeError { message: &message }];

            state.serialize_field("errors", &errors)?;
        }

        state.end()
    }
}

impl Serialize for SerializeError<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("ErrorMessage", 1)?;

        state.serialize_field("message", &self.message)?;
        state.end()
    }
}