volga 0.9.1

Easy & Fast Web Framework for Rust
Documentation
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
//! Error Handling tools

use hyper::http::status::InvalidStatusCode;

use std::{
    convert::Infallible,
    error::Error as StdError,
    fmt,
    io::{Error as IoError, ErrorKind},
};

use super::{
    App,
    http::{FromRawRequest, FromRequestParts, GenericHandler, IntoResponse, MapErr, StatusCode},
};

pub use self::{
    fallback::{FallbackFunc, FallbackHandler},
    handler::{ErrorFunc, ErrorHandler},
};

#[cfg(feature = "problem-details")]
pub use self::problem::{Problem, ProblemDetails};

pub mod fallback;
pub mod handler;
#[cfg(feature = "problem-details")]
pub mod problem;

pub(crate) type BoxError = Box<dyn StdError + Send + Sync>;

/// Generic error
#[derive(Debug)]
pub struct Error {
    /// HTTP status code
    pub(crate) status: StatusCode,

    /// An instance where this error happened
    pub(crate) instance: Option<String>,

    /// Inner error object
    pub(crate) inner: BoxError,
}

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

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        Some(self.inner.as_ref())
    }
}

impl From<Infallible> for Error {
    #[inline]
    fn from(infallible: Infallible) -> Error {
        match infallible {}
    }
}

impl From<serde_json::Error> for Error {
    #[inline]
    fn from(err: serde_json::Error) -> Error {
        Self {
            status: StatusCode::BAD_REQUEST,
            inner: err.into(),
            instance: None,
        }
    }
}

impl From<serde_urlencoded::ser::Error> for Error {
    #[inline]
    fn from(err: serde_urlencoded::ser::Error) -> Error {
        Self {
            status: StatusCode::BAD_REQUEST,
            inner: err.into(),
            instance: None,
        }
    }
}

impl From<IoError> for Error {
    #[inline]
    fn from(err: IoError) -> Self {
        let kind = err.kind();

        if kind == ErrorKind::Other {
            if let Some(inner) = err.into_inner() {
                return match inner.downcast::<Error>() {
                    Ok(volga) => *volga,
                    Err(inner) => {
                        let err = IoError::new(kind, inner);
                        Error::from_io_error_fallback(err)
                    }
                };
            }

            let err = IoError::new(kind, "io error (Other)");
            return Error::from_io_error_fallback(err);
        }

        Error::from_io_error_fallback(err)
    }
}

impl From<hyper::http::Error> for Error {
    #[inline]
    fn from(err: hyper::http::Error) -> Self {
        Self {
            instance: None,
            inner: err.into(),
            status: StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl From<Error> for IoError {
    #[inline]
    fn from(err: Error) -> Self {
        Self::other(err)
    }
}

impl From<fmt::Error> for Error {
    #[inline]
    fn from(err: fmt::Error) -> Self {
        Self {
            status: StatusCode::BAD_REQUEST,
            inner: err.into(),
            instance: None,
        }
    }
}

impl From<InvalidStatusCode> for Error {
    #[inline]
    fn from(err: InvalidStatusCode) -> Self {
        Self {
            status: StatusCode::BAD_REQUEST,
            inner: err.into(),
            instance: None,
        }
    }
}

impl Error {
    /// Creates a new [`Error`]
    pub fn new(instance: &str, err: impl Into<BoxError>) -> Self {
        Self {
            status: StatusCode::INTERNAL_SERVER_ERROR,
            inner: err.into(),
            instance: Some(instance.into()),
        }
    }

    /// Creates an internal server error
    #[inline]
    pub fn server_error(err: impl Into<BoxError>) -> Self {
        Self {
            status: StatusCode::INTERNAL_SERVER_ERROR,
            inner: err.into(),
            instance: None,
        }
    }

    /// Creates a client error
    #[inline]
    pub fn client_error(err: impl Into<BoxError>) -> Self {
        Self {
            status: StatusCode::BAD_REQUEST,
            inner: err.into(),
            instance: None,
        }
    }

    /// Creates [`Error`] from status code, instance and underlying error
    #[inline]
    pub fn from_parts(
        status: StatusCode,
        instance: Option<String>,
        err: impl Into<BoxError>,
    ) -> Self {
        Self {
            status,
            instance,
            inner: err.into(),
        }
    }

    /// Returns HTTP status code of this error
    #[inline]
    pub fn status(&self) -> StatusCode {
        self.status
    }

    /// Returns an instance where this error happened
    #[inline]
    pub fn instance(&self) -> Option<&str> {
        self.instance.as_deref()
    }

    /// Unwraps the inner error
    pub fn into_inner(self) -> BoxError {
        self.inner
    }

    /// Unwraps the error into a tuple of status code, instance value and underlying error
    pub fn into_parts(self) -> (StatusCode, Option<String>, BoxError) {
        (self.status, self.instance, self.inner)
    }

    /// Check if the status is within 500-599.
    #[inline]
    pub fn is_server_error(&self) -> bool {
        self.status.is_server_error()
    }

    /// Check if the status is within 400-499.
    #[inline]
    pub fn is_client_error(&self) -> bool {
        self.status.is_client_error()
    }

    #[inline]
    fn from_io_error_fallback(err: IoError) -> Self {
        let status = match err.kind() {
            ErrorKind::NotFound => StatusCode::NOT_FOUND,
            ErrorKind::PermissionDenied => StatusCode::FORBIDDEN,

            ErrorKind::ConnectionRefused
            | ErrorKind::ConnectionReset
            | ErrorKind::ConnectionAborted
            | ErrorKind::NotConnected
            | ErrorKind::AddrInUse
            | ErrorKind::AddrNotAvailable
            | ErrorKind::BrokenPipe => StatusCode::BAD_GATEWAY,

            ErrorKind::AlreadyExists => StatusCode::CONFLICT,
            ErrorKind::InvalidInput | ErrorKind::InvalidData => StatusCode::BAD_REQUEST,
            ErrorKind::TimedOut => StatusCode::REQUEST_TIMEOUT,
            ErrorKind::Unsupported => StatusCode::UNSUPPORTED_MEDIA_TYPE,

            _ => StatusCode::INTERNAL_SERVER_ERROR,
        };

        Self {
            instance: None,
            inner: err.into(),
            status,
        }
    }
}

impl App {
    /// Adds a global error handler
    ///
    /// # Example
    /// ```no_run
    ///  use volga::{App, error::Error, status};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> std::io::Result<()> {
    ///  let mut app = App::new();
    ///  
    ///  app.map_err(|error: Error| async move {
    ///     status!(500, { "error_message:": error.to_string() })
    ///  });
    /// # app.run().await
    /// # }
    /// ```
    pub fn map_err<F, R, Args>(&mut self, handler: F) -> &mut Self
    where
        F: MapErr<Args, Output = R>,
        R: IntoResponse + 'static,
        Args: FromRequestParts + Send + 'static,
    {
        self.pipeline
            .set_error_handler(ErrorFunc::new(handler).into());
        self
    }

    /// Adds a special fallback handler that handles the unregistered paths
    ///
    /// # Example
    /// ```no_run
    /// use volga::{App, error::Error, not_found};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> std::io::Result<()> {
    ///  let mut app = App::new();
    ///  
    ///  app.map_fallback(|| async {
    ///     not_found!()
    ///  });
    /// # app.run().await
    /// # }
    /// ```
    pub fn map_fallback<F, Args, R>(&mut self, handler: F) -> &mut Self
    where
        F: GenericHandler<Args, Output = R>,
        Args: FromRawRequest + Send + 'static,
        R: IntoResponse,
    {
        self.pipeline
            .set_fallback_handler(FallbackFunc::new(handler).into());
        self
    }
}

#[cfg(test)]
mod tests {
    use super::{Error, StatusCode};
    use std::io::{Error as IoError, ErrorKind};

    #[test]
    fn it_creates_new_error() {
        let err = Error::new("/api", "some error");

        assert!(err.is_server_error());
        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(err.instance().unwrap(), "/api");
    }

    #[test]
    fn it_converts_from_not_found_io_error() {
        let io_error = IoError::new(ErrorKind::NotFound, "not found");
        let err = Error::from(io_error);

        assert!(err.is_client_error());
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_connection_reset_io_error() {
        let io_error = IoError::new(ErrorKind::ConnectionReset, "reset");
        let err = Error::from(io_error);

        assert!(err.is_server_error());
        assert_eq!(err.status(), StatusCode::BAD_GATEWAY);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_connection_aborted_io_error() {
        let io_error = IoError::new(ErrorKind::ConnectionAborted, "aborted");
        let err = Error::from(io_error);

        assert!(err.is_server_error());
        assert_eq!(err.status(), StatusCode::BAD_GATEWAY);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_not_connected_io_error() {
        let io_error = IoError::new(ErrorKind::NotConnected, "not connected");
        let err = Error::from(io_error);

        assert!(err.is_server_error());
        assert_eq!(err.status(), StatusCode::BAD_GATEWAY);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_add_in_use_io_error() {
        let io_error = IoError::new(ErrorKind::AddrInUse, "addr in use");
        let err = Error::from(io_error);

        assert!(err.is_server_error());
        assert_eq!(err.status(), StatusCode::BAD_GATEWAY);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_addr_not_available_io_error() {
        let io_error = IoError::new(ErrorKind::AddrNotAvailable, "addr not available");
        let err = Error::from(io_error);

        assert!(err.is_server_error());
        assert_eq!(err.status(), StatusCode::BAD_GATEWAY);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_broken_pipe_io_error() {
        let io_error = IoError::new(ErrorKind::BrokenPipe, "broken pipe");
        let err = Error::from(io_error);

        assert!(err.is_server_error());
        assert_eq!(err.status(), StatusCode::BAD_GATEWAY);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_already_exists_io_error() {
        let io_error = IoError::new(ErrorKind::AlreadyExists, "exists");
        let err = Error::from(io_error);

        assert!(err.is_client_error());
        assert_eq!(err.status(), StatusCode::CONFLICT);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_invalid_data_io_error() {
        let io_error = IoError::new(ErrorKind::InvalidData, "invalid data");
        let err = Error::from(io_error);

        assert!(err.is_client_error());
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_timed_out_io_error() {
        let io_error = IoError::new(ErrorKind::TimedOut, "timeout");
        let err = Error::from(io_error);

        assert!(err.is_client_error());
        assert_eq!(err.status(), StatusCode::REQUEST_TIMEOUT);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_unsupported_io_error() {
        let io_error = IoError::new(ErrorKind::Unsupported, "unsupported");
        let err = Error::from(io_error);

        assert!(err.is_client_error());
        assert_eq!(err.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_permission_denied_io_error() {
        let io_error = IoError::new(ErrorKind::PermissionDenied, "forbidden");
        let err = Error::from(io_error);

        assert!(err.is_client_error());
        assert_eq!(err.status(), StatusCode::FORBIDDEN);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_connection_refused_io_error() {
        let io_error = IoError::new(ErrorKind::ConnectionRefused, "connection refused");
        let err = Error::from(io_error);

        assert!(err.is_server_error());
        assert_eq!(err.status(), StatusCode::BAD_GATEWAY);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_io_error() {
        let io_error = IoError::other("some error");
        let err = Error::from(io_error);

        assert!(err.is_server_error());
        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_error_to_io_error() {
        let error = Error::client_error("some error");
        let io_error = IoError::from(error);

        assert_eq!(io_error.kind(), ErrorKind::Other);
    }

    #[test]
    fn it_splits_into_parts() {
        let error = Error::server_error("some error");

        let (status, instance, inner) = error.into_parts();

        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert!(instance.is_none());
        assert_eq!(format!("{inner}"), "some error");
    }

    #[test]
    fn it_unwraps_into_inner() {
        let error = Error::server_error("some error");

        let inner = error.into_inner();

        assert_eq!(format!("{inner}"), "some error");
    }

    #[test]
    #[allow(clippy::default_constructed_unit_structs)]
    fn it_converts_from_fmt_error() {
        let fmt_error = std::fmt::Error::default();
        let err = Error::from(fmt_error);

        assert!(err.is_client_error());
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert_eq!(err.instance(), None);
    }

    #[test]
    fn it_converts_from_io_error_with_inner_volga_error() {
        let io_error = IoError::other(Error::client_error("some error"));
        let err = Error::from(io_error);

        assert!(err.is_client_error());
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert_eq!(err.instance(), None);
    }
}