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
use std::fmt;
use std::io::Cursor;

use crate::http::uri::Path;
use crate::http::ext::IntoOwned;
use crate::response::Response;
use crate::request::Request;
use crate::http::{Status, ContentType, uri};
use crate::catcher::{Handler, BoxFuture};

use yansi::Paint;

/// An error catching route.
///
/// Catchers are routes that run when errors are produced by the application.
/// They consist of a [`Handler`] and an optional status code to match against
/// arising errors. Errors arise from the the following sources:
///
///   * A failing guard.
///   * A failing responder.
///   * A forwarding guard.
///   * Routing failure.
///
/// Each error or forward is paired with a status code. Guards and responders
/// indicate the status code themselves via their `Err` and `Outcome` return
/// value. A complete routing failure is always a `404`. Rocket invokes the
/// error handler for the catcher with an error's status code, or in the case of
/// every route resulting in a forward, the last forwarded status code.
///
/// ### Error Handler Restrictions
///
/// Because error handlers are a last resort, they should not fail to produce a
/// response. If an error handler _does_ fail, Rocket invokes its default `500`
/// error catcher. Error handlers cannot forward.
///
/// # Routing
///
/// If a route fails by returning an error [`Outcome`], Rocket routes the
/// erroring request to the highest precedence catcher among all the catchers
/// that [match](Catcher::matches()). See [`Catcher::matches()`] for details on
/// matching. Precedence is determined by the catcher's _base_, which is
/// provided as the first argument to [`Rocket::register()`]. Catchers with more
/// non-empty segments have a higher precedence.
///
/// Rocket provides [built-in defaults](#built-in-default), but _default_
/// catchers can also be registered. A _default_ catcher is a catcher with no
/// explicit status code: `None`.
///
/// [`Outcome`]: crate::request::Outcome
/// [`Rocket::register()`]: crate::Rocket::register()
///
/// ## Collisions
///
/// Two catchers are said to _collide_ if there exists an error that matches
/// both catchers. Colliding catchers present a routing ambiguity and are thus
/// disallowed by Rocket. Because catchers can be constructed dynamically,
/// collision checking is done at [`ignite`](crate::Rocket::ignite()) time,
/// after it becomes statically impossible to register any more catchers on an
/// instance of `Rocket`.
///
/// ## Built-In Default
///
/// Rocket's provides a built-in default catcher that can handle all errors. It
/// produces HTML or JSON, depending on the value of the `Accept` header. As
/// such, catchers only need to be registered if an error needs to be handled in
/// a custom fashion. The built-in default never conflicts with any
/// user-registered catchers.
///
/// # Code Generation
///
/// Catchers should rarely be constructed or used directly. Instead, they are
/// typically generated via the [`catch`] attribute, as follows:
///
/// ```rust,no_run
/// #[macro_use] extern crate rocket;
///
/// use rocket::Request;
/// use rocket::http::Status;
///
/// #[catch(500)]
/// fn internal_error() -> &'static str {
///     "Whoops! Looks like we messed up."
/// }
///
/// #[catch(404)]
/// fn not_found(req: &Request) -> String {
///     format!("I couldn't find '{}'. Try something else?", req.uri())
/// }
///
/// #[catch(default)]
/// fn default(status: Status, req: &Request) -> String {
///     format!("{} ({})", status, req.uri())
/// }
///
/// #[launch]
/// fn rocket() -> _ {
///     rocket::build().register("/", catchers![internal_error, not_found, default])
/// }
/// ```
///
/// A function decorated with `#[catch]` may take zero, one, or two arguments.
/// It's type signature must be one of the following, where `R:`[`Responder`]:
///
///   * `fn() -> R`
///   * `fn(`[`&Request`]`) -> R`
///   * `fn(`[`Status`]`, `[`&Request`]`) -> R`
///
/// See the [`catch`] documentation for full details.
///
/// [`catch`]: crate::catch
/// [`Responder`]: crate::response::Responder
/// [`&Request`]: crate::request::Request
/// [`Status`]: crate::http::Status
#[derive(Clone)]
pub struct Catcher {
    /// The name of this catcher, if one was given.
    pub name: Option<Cow<'static, str>>,

    /// The HTTP status to match against if this route is not `default`.
    pub code: Option<u16>,

    /// The catcher's associated error handler.
    pub handler: Box<dyn Handler>,

    /// The mount point.
    pub(crate) base: uri::Origin<'static>,

    /// The catcher's calculated rank.
    ///
    /// This is -(number of nonempty segments in base).
    pub(crate) rank: isize,
}

// The rank is computed as -(number of nonempty segments in base) => catchers
// with more nonempty segments have lower ranks => higher precedence.
fn rank(base: Path<'_>) -> isize {
    -1 * (base.segments().filter(|s| !s.is_empty()).count() as isize)
}

impl Catcher {
    /// Creates a catcher for the given `status`, or a default catcher if
    /// `status` is `None`, using the given error handler. This should only be
    /// used when routing manually.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rocket::request::Request;
    /// use rocket::catcher::{Catcher, BoxFuture};
    /// use rocket::response::Responder;
    /// use rocket::http::Status;
    ///
    /// fn handle_404<'r>(status: Status, req: &'r Request<'_>) -> BoxFuture<'r> {
    ///    let res = (status, format!("404: {}", req.uri()));
    ///    Box::pin(async move { res.respond_to(req) })
    /// }
    ///
    /// fn handle_500<'r>(_: Status, req: &'r Request<'_>) -> BoxFuture<'r> {
    ///     Box::pin(async move{ "Whoops, we messed up!".respond_to(req) })
    /// }
    ///
    /// fn handle_default<'r>(status: Status, req: &'r Request<'_>) -> BoxFuture<'r> {
    ///    let res = (status, format!("{}: {}", status, req.uri()));
    ///    Box::pin(async move { res.respond_to(req) })
    /// }
    ///
    /// let not_found_catcher = Catcher::new(404, handle_404);
    /// let internal_server_error_catcher = Catcher::new(500, handle_500);
    /// let default_error_catcher = Catcher::new(None, handle_default);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `code` is not in the HTTP status code error range `[400,
    /// 600)`.
    #[inline(always)]
    pub fn new<S, H>(code: S, handler: H) -> Catcher
        where S: Into<Option<u16>>, H: Handler
    {
        let code = code.into();
        if let Some(code) = code {
            assert!(code >= 400 && code < 600);
        }

        Catcher {
            name: None,
            base: uri::Origin::ROOT,
            handler: Box::new(handler),
            rank: rank(uri::Origin::ROOT.path()),
            code
        }
    }

    /// Returns the mount point (base) of the catcher, which defaults to `/`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket::request::Request;
    /// use rocket::catcher::{Catcher, BoxFuture};
    /// use rocket::response::Responder;
    /// use rocket::http::Status;
    ///
    /// fn handle_404<'r>(status: Status, req: &'r Request<'_>) -> BoxFuture<'r> {
    ///    let res = (status, format!("404: {}", req.uri()));
    ///    Box::pin(async move { res.respond_to(req) })
    /// }
    ///
    /// let catcher = Catcher::new(404, handle_404);
    /// assert_eq!(catcher.base(), "/");
    ///
    /// let catcher = catcher.map_base(|base| format!("/foo/bar/{}", base)).unwrap();
    /// assert_eq!(catcher.base(), "/foo/bar");
    /// ```
    pub fn base(&self) -> Path<'_> {
        self.base.path()
    }

    /// Prefix `base` to the current `base` in `self.`
    ///
    /// If the the current base is `/`, then the base is replaced by `base`.
    /// Otherwise, `base` is prefixed to the existing `base`.
    ///
    /// ```rust
    /// use rocket::request::Request;
    /// use rocket::catcher::{Catcher, BoxFuture};
    /// use rocket::response::Responder;
    /// use rocket::http::Status;
    /// # use rocket::uri;
    ///
    /// fn handle_404<'r>(status: Status, req: &'r Request<'_>) -> BoxFuture<'r> {
    ///    let res = (status, format!("404: {}", req.uri()));
    ///    Box::pin(async move { res.respond_to(req) })
    /// }
    ///
    /// let catcher = Catcher::new(404, handle_404);
    /// assert_eq!(catcher.base(), "/");
    ///
    /// // Since the base is `/`, rebasing replaces the base.
    /// let rebased = catcher.rebase(uri!("/boo"));
    /// assert_eq!(rebased.base(), "/boo");
    ///
    /// // Now every rebase prefixes.
    /// let rebased = rebased.rebase(uri!("/base"));
    /// assert_eq!(rebased.base(), "/base/boo");
    ///
    /// // Note that trailing slashes have no effect and are thus removed:
    /// let catcher = Catcher::new(404, handle_404);
    /// let rebased = catcher.rebase(uri!("/boo/"));
    /// assert_eq!(rebased.base(), "/boo");
    /// ```
    pub fn rebase(mut self, mut base: uri::Origin<'_>) -> Self {
        self.base = if self.base.path() == "/" {
            base.clear_query();
            base.into_normalized_nontrailing().into_owned()
        } else {
            uri::Origin::parse_owned(format!("{}{}", base.path(), self.base))
                .expect("catcher rebase: {new}{old} is valid origin URI")
                .into_normalized_nontrailing()
        };

        self.rank = rank(self.base());
        self
    }

    /// Maps the `base` of this catcher using `mapper`, returning a new
    /// `Catcher` with the returned base.
    ///
    /// **Note:** Prefer to use [`Catcher::rebase()`] whenever possible!
    ///
    /// `mapper` is called with the current base. The returned `String` is used
    /// as the new base if it is a valid URI. If the returned base URI contains
    /// a query, it is ignored. Returns an error if the base produced by
    /// `mapper` is not a valid origin URI.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket::request::Request;
    /// use rocket::catcher::{Catcher, BoxFuture};
    /// use rocket::response::Responder;
    /// use rocket::http::Status;
    ///
    /// fn handle_404<'r>(status: Status, req: &'r Request<'_>) -> BoxFuture<'r> {
    ///    let res = (status, format!("404: {}", req.uri()));
    ///    Box::pin(async move { res.respond_to(req) })
    /// }
    ///
    /// let catcher = Catcher::new(404, handle_404);
    /// assert_eq!(catcher.base(), "/");
    ///
    /// let catcher = catcher.map_base(|_| format!("/bar")).unwrap();
    /// assert_eq!(catcher.base(), "/bar");
    ///
    /// let catcher = catcher.map_base(|base| format!("/foo{}", base)).unwrap();
    /// assert_eq!(catcher.base(), "/foo/bar");
    ///
    /// let catcher = catcher.map_base(|base| format!("/foo ? {}", base));
    /// assert!(catcher.is_err());
    /// ```
    pub fn map_base<'a, F>(mut self, mapper: F) -> Result<Self, uri::Error<'static>>
        where F: FnOnce(uri::Origin<'a>) -> String
    {
        let new_base = uri::Origin::parse_owned(mapper(self.base))?;
        self.base = new_base.into_normalized_nontrailing();
        self.base.clear_query();
        self.rank = rank(self.base());
        Ok(self)
    }
}

impl Default for Catcher {
    fn default() -> Self {
        fn handler<'r>(s: Status, req: &'r Request<'_>) -> BoxFuture<'r> {
            Box::pin(async move { Ok(default_handler(s, req)) })
        }

        let mut catcher = Catcher::new(None, handler);
        catcher.name = Some("<Rocket Catcher>".into());
        catcher
    }
}

/// Information generated by the `catch` attribute during codegen.
#[doc(hidden)]
pub struct StaticInfo {
    /// The catcher's name, i.e, the name of the function.
    pub name: &'static str,
    /// The catcher's status code.
    pub code: Option<u16>,
    /// The catcher's handler, i.e, the annotated function.
    pub handler: for<'r> fn(Status, &'r Request<'_>) -> BoxFuture<'r>,
}

#[doc(hidden)]
impl From<StaticInfo> for Catcher {
    #[inline]
    fn from(info: StaticInfo) -> Catcher {
        let mut catcher = Catcher::new(info.code, info.handler);
        catcher.name = Some(info.name.into());
        catcher
    }
}

impl fmt::Display for Catcher {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(ref n) = self.name {
            write!(f, "{}{}{} ", "(".cyan(), n.primary(), ")".cyan())?;
        }

        write!(f, "{} ", self.base.path().green())?;

        match self.code {
            Some(code) => write!(f, "{}", code.blue()),
            None => write!(f, "{}", "default".blue()),
        }
    }
}

impl fmt::Debug for Catcher {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Catcher")
            .field("name", &self.name)
            .field("base", &self.base)
            .field("code", &self.code)
            .field("rank", &self.rank)
            .finish()
    }
}

macro_rules! html_error_template {
    ($code:expr, $reason:expr, $description:expr) => (
        concat!(
r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="color-scheme" content="light dark">
    <title>"#, $code, " ", $reason, r#"</title>
</head>
<body align="center">
    <div role="main" align="center">
        <h1>"#, $code, ": ", $reason, r#"</h1>
        <p>"#, $description, r#"</p>
        <hr />
    </div>
    <div role="contentinfo" align="center">
        <small>Rocket</small>
    </div>
</body>
</html>"#
        )
    )
}

macro_rules! json_error_template {
    ($code:expr, $reason:expr, $description:expr) => (
        concat!(
r#"{
  "error": {
    "code": "#, $code, r#",
    "reason": ""#, $reason, r#"",
    "description": ""#, $description, r#""
  }
}"#
        )
    )
}

// This is unfortunate, but the `{`, `}` above make it unusable for `format!`.
macro_rules! json_error_fmt_template {
    ($code:expr, $reason:expr, $description:expr) => (
        concat!(
r#"{{
  "error": {{
    "code": "#, $code, r#",
    "reason": ""#, $reason, r#"",
    "description": ""#, $description, r#""
  }}
}}"#
        )
    )
}

macro_rules! default_handler_fn {
    ($($code:expr, $reason:expr, $description:expr),+) => (
        use std::borrow::Cow;

        pub(crate) fn default_handler<'r>(
            status: Status,
            req: &'r Request<'_>
        ) -> Response<'r> {
            let preferred = req.accept().map(|a| a.preferred());
            let (mime, text) = if preferred.map_or(false, |a| a.is_json()) {
                let json: Cow<'_, str> = match status.code {
                    $($code => json_error_template!($code, $reason, $description).into(),)*
                    code => format!(json_error_fmt_template!("{}", "Unknown Error",
                            "An unknown error has occurred."), code).into()
                };

                (ContentType::JSON, json)
            } else {
                let html: Cow<'_, str> = match status.code {
                    $($code => html_error_template!($code, $reason, $description).into(),)*
                    code => format!(html_error_template!("{}", "Unknown Error",
                            "An unknown error has occurred."), code, code).into(),
                };

                (ContentType::HTML, html)
            };

            let mut r = Response::build().status(status).header(mime).finalize();
            match text {
                Cow::Owned(v) => r.set_sized_body(v.len(), Cursor::new(v)),
                Cow::Borrowed(v) => r.set_sized_body(v.len(), Cursor::new(v)),
            };

            r
        }
    )
}

default_handler_fn! {
    400, "Bad Request", "The request could not be understood by the server due \
        to malformed syntax.",
    401, "Unauthorized", "The request requires user authentication.",
    402, "Payment Required", "The request could not be processed due to lack of payment.",
    403, "Forbidden", "The server refused to authorize the request.",
    404, "Not Found", "The requested resource could not be found.",
    405, "Method Not Allowed", "The request method is not supported for the requested resource.",
    406, "Not Acceptable", "The requested resource is capable of generating only content not \
        acceptable according to the Accept headers sent in the request.",
    407, "Proxy Authentication Required", "Authentication with the proxy is required.",
    408, "Request Timeout", "The server timed out waiting for the request.",
    409, "Conflict", "The request could not be processed because of a conflict in the request.",
    410, "Gone", "The resource requested is no longer available and will not be available again.",
    411, "Length Required", "The request did not specify the length of its content, which is \
        required by the requested resource.",
    412, "Precondition Failed", "The server does not meet one of the \
        preconditions specified in the request.",
    413, "Payload Too Large", "The request is larger than the server is \
        willing or able to process.",
    414, "URI Too Long", "The URI provided was too long for the server to process.",
    415, "Unsupported Media Type", "The request entity has a media type which \
        the server or resource does not support.",
    416, "Range Not Satisfiable", "The portion of the requested file cannot be \
        supplied by the server.",
    417, "Expectation Failed", "The server cannot meet the requirements of the \
        Expect request-header field.",
    418, "I'm a teapot", "I was requested to brew coffee, and I am a teapot.",
    421, "Misdirected Request", "The server cannot produce a response for this request.",
    422, "Unprocessable Entity", "The request was well-formed but was unable to \
        be followed due to semantic errors.",
    426, "Upgrade Required", "Switching to the protocol in the Upgrade header field is required.",
    428, "Precondition Required", "The server requires the request to be conditional.",
    429, "Too Many Requests", "Too many requests have been received recently.",
    431, "Request Header Fields Too Large", "The server is unwilling to process \
        the request because either an individual header field, or all the header \
        fields collectively, are too large.",
    451, "Unavailable For Legal Reasons", "The requested resource is unavailable \
        due to a legal demand to deny access to this resource.",
    500, "Internal Server Error", "The server encountered an internal error while \
        processing this request.",
    501, "Not Implemented", "The server either does not recognize the request \
        method, or it lacks the ability to fulfill the request.",
    503, "Service Unavailable", "The server is currently unavailable.",
    504, "Gateway Timeout", "The server did not receive a timely response from an upstream server.",
    510, "Not Extended", "Further extensions to the request are required for \
        the server to fulfill it."
}