rocket/catcher/handler.rs
1use crate::{Request, Response};
2use crate::http::Status;
3
4/// Type alias for the return type of a [`Catcher`](crate::Catcher)'s
5/// [`Handler::handle()`].
6pub type Result<'r> = std::result::Result<Response<'r>, crate::http::Status>;
7
8/// Type alias for the return type of a _raw_ [`Catcher`](crate::Catcher)'s
9/// [`Handler`].
10pub type BoxFuture<'r, T = Result<'r>> = futures::future::BoxFuture<'r, T>;
11
12/// Trait implemented by [`Catcher`](crate::Catcher) error handlers.
13///
14/// This trait is exactly like a [`Route`](crate::Route)'s
15/// [`Handler`](crate::route::Handler) except it handles errors instead of
16/// requests. Thus, the documentation for
17/// [`route::Handler`](crate::route::Handler) applies to this trait as well. We
18/// defer to it for full details.
19///
20/// ## Async Trait
21///
22/// This is an _async_ trait. Implementations must be decorated
23/// [`#[rocket::async_trait]`](crate::async_trait).
24///
25/// # Example
26///
27/// Say you'd like to write a handler that changes its functionality based on a
28/// `Kind` enum value that the user provides. Such a handler might be written
29/// and used as follows:
30///
31/// ```rust,no_run
32/// use rocket::{Request, Catcher, catcher};
33/// use rocket::response::{Response, Responder};
34/// use rocket::http::Status;
35///
36/// #[derive(Copy, Clone)]
37/// enum Kind {
38/// Simple,
39/// Intermediate,
40/// Complex,
41/// }
42///
43/// #[derive(Clone)]
44/// struct CustomHandler(Kind);
45///
46/// #[rocket::async_trait]
47/// impl catcher::Handler for CustomHandler {
48/// async fn handle<'r>(&self, status: Status, req: &'r Request<'_>) -> catcher::Result<'r> {
49/// let inner = match self.0 {
50/// Kind::Simple => "simple".respond_to(req)?,
51/// Kind::Intermediate => "intermediate".respond_to(req)?,
52/// Kind::Complex => "complex".respond_to(req)?,
53/// };
54///
55/// Response::build_from(inner).status(status).ok()
56/// }
57/// }
58///
59/// impl CustomHandler {
60/// /// Returns a `default` catcher that uses `CustomHandler`.
61/// fn default(kind: Kind) -> Vec<Catcher> {
62/// vec![Catcher::new(None, CustomHandler(kind))]
63/// }
64///
65/// /// Returns a catcher for code `status` that uses `CustomHandler`.
66/// fn catch(status: Status, kind: Kind) -> Vec<Catcher> {
67/// vec![Catcher::new(status.code, CustomHandler(kind))]
68/// }
69/// }
70///
71/// #[rocket::launch]
72/// fn rocket() -> _ {
73/// rocket::build()
74/// // to handle only `404`
75/// .register("/", CustomHandler::catch(Status::NotFound, Kind::Simple))
76/// // or to register as the default
77/// .register("/", CustomHandler::default(Kind::Simple))
78/// }
79/// ```
80///
81/// Note the following:
82///
83/// 1. `CustomHandler` implements `Clone`. This is required so that
84/// `CustomHandler` implements `Cloneable` automatically. The `Cloneable`
85/// trait serves no other purpose but to ensure that every `Handler`
86/// can be cloned, allowing `Catcher`s to be cloned.
87/// 2. `CustomHandler`'s methods return `Vec<Route>`, allowing for use
88/// directly as the parameter to `rocket.register("/", )`.
89/// 3. Unlike static-function-based handlers, this custom handler can make use
90/// of internal state.
91#[crate::async_trait]
92pub trait Handler: Cloneable + Send + Sync + 'static {
93 /// Called by Rocket when an error with `status` for a given `Request`
94 /// should be handled by this handler.
95 ///
96 /// Error handlers _should not_ fail and thus _should_ always return `Ok`.
97 /// Nevertheless, failure is allowed, both for convenience and necessity. If
98 /// an error handler fails, Rocket's default `500` catcher is invoked. If it
99 /// succeeds, the returned `Response` is used to respond to the client.
100 async fn handle<'r>(&self, status: Status, req: &'r Request<'_>) -> Result<'r>;
101}
102
103// We write this manually to avoid double-boxing.
104impl<F: Clone + Sync + Send + 'static> Handler for F
105 where for<'x> F: Fn(Status, &'x Request<'_>) -> BoxFuture<'x>,
106{
107 fn handle<'r, 'life0, 'life1, 'async_trait>(
108 &'life0 self,
109 status: Status,
110 req: &'r Request<'life1>,
111 ) -> BoxFuture<'r>
112 where 'r: 'async_trait,
113 'life0: 'async_trait,
114 'life1: 'async_trait,
115 Self: 'async_trait,
116 {
117 self(status, req)
118 }
119}
120
121#[cfg(test)]
122pub fn dummy_handler<'r>(_: Status, _: &'r Request<'_>) -> BoxFuture<'r> {
123 Box::pin(async move { Ok(Response::new()) })
124}
125
126mod private {
127 pub trait Sealed {}
128 impl<T: super::Handler + Clone> Sealed for T {}
129}
130
131/// Helper trait to make a [`Catcher`](crate::Catcher)'s `Box<dyn Handler>`
132/// `Clone`.
133///
134/// This trait cannot be implemented directly. Instead, implement `Clone` and
135/// [`Handler`]; all types that implement `Clone` and `Handler` automatically
136/// implement `Cloneable`.
137pub trait Cloneable: private::Sealed {
138 #[doc(hidden)]
139 fn clone_handler(&self) -> Box<dyn Handler>;
140}
141
142impl<T: Handler + Clone> Cloneable for T {
143 fn clone_handler(&self) -> Box<dyn Handler> {
144 Box::new(self.clone())
145 }
146}
147
148impl Clone for Box<dyn Handler> {
149 fn clone(&self) -> Box<dyn Handler> {
150 self.clone_handler()
151 }
152}