Skip to content

Commit 546eea0

Browse files
committed
Remove explicit status parameter in most cases
1 parent c787f64 commit 546eea0

File tree

35 files changed

+188
-183
lines changed

35 files changed

+188
-183
lines changed

contrib/db_pools/lib/src/database.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,9 @@ pub enum ConnectionError<E> {
287287
}
288288

289289
#[rocket::async_trait]
290-
impl<'r, D: Database> FromRequest<'r> for Connection<D> {
290+
impl<'r, D: Database> FromRequest<'r> for Connection<D>
291+
where <D::Pool as Pool>::Error: Send + Sync,
292+
{
291293
type Error = ConnectionError<<D::Pool as Pool>::Error>;
292294

293295
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {

contrib/db_pools/lib/src/diesel.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
//! # #[macro_use] extern crate rocket;
2828
//! # #[cfg(feature = "diesel_mysql")] {
2929
//! use rocket_db_pools::{Database, Connection};
30-
//! use rocket_db_pools::diesel::{QueryResult, MysqlPool, prelude::*};
30+
//! use rocket_db_pools::diesel::{QueryResult, DieselError, MysqlPool, prelude::*};
3131
//!
3232
//! #[derive(Database)]
3333
//! #[database("diesel_mysql")]
@@ -58,6 +58,11 @@
5858
//!
5959
//! Ok(format!("{post_ids:?}"))
6060
//! }
61+
//!
62+
//! #[catch(500, error = "<e>")]
63+
//! fn catch_diesel_error(e: &DieselError) -> String {
64+
//! format!("{e:?}")
65+
//! }
6166
//! # }
6267
//! ```
6368
@@ -117,17 +122,14 @@ impl From<diesel::result::Error> for DieselError {
117122
}
118123
}
119124

120-
/// Alias of a `Result` with an error type of [`Debug`] for a `diesel::Error`.
125+
/// Alias of a `Result` with an error type of `diesel::Error`.
121126
///
122127
/// `QueryResult` is a [`Responder`](rocket::response::Responder) when `T` (the
123128
/// `Ok` value) is a `Responder`. By using this alias as a route handler's
124129
/// return type, the `?` operator can be applied to fallible `diesel` functions
125130
/// in the route handler while still providing a valid `Responder` return type.
126131
///
127-
/// See the [module level docs](self#example) for a usage example.
128-
///
129-
/// [`Debug`]: rocket::response::Debug
130-
// TODO: this needs to change
132+
/// See module level docs for usage, and catching the error type.
131133
pub type QueryResult<T, E = DieselError> = Result<T, E>;
132134

133135
/// Type alias for an `async` pool of MySQL connections for `async` [diesel].

contrib/dyn_templates/src/template.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -265,21 +265,20 @@ impl Template {
265265
/// extension and a fixed-size body containing the rendered template. If
266266
/// rendering fails, an `Err` of `Status::InternalServerError` is returned.
267267
impl<'r> Responder<'r, 'static> for Template {
268-
// TODO: typed: This should be a more useful type
269-
type Error = std::convert::Infallible;
270-
fn respond_to(self, req: &'r Request<'_>) -> response::Outcome<'static, Self::Error> {
268+
type Error = Status;
269+
fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static, Self::Error> {
271270
if let Some(ctxt) = req.rocket().state::<ContextManager>() {
272271
match self.finalize(&ctxt.context()) {
273-
Ok(v) => v.respond_to(req),
274-
Err(s) => response::Outcome::Forward(s),
272+
Ok(v) => v.respond_to(req).map_err(|e| match e {}),
273+
Err(s) => Err(s),
275274
}
276275
} else {
277276
error!(
278277
"uninitialized template context: missing `Template::fairing()`.\n\
279278
To use templates, you must attach `Template::fairing()`."
280279
);
281280

282-
response::Outcome::Forward(Status::InternalServerError)
281+
Err(Status::InternalServerError)
283282
}
284283
}
285284
}

contrib/ws/src/websocket.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ impl<'r> FromRequest<'r> for WebSocket {
239239

240240
impl<'r, 'o: 'r> Responder<'r, 'o> for Channel<'o> {
241241
type Error = std::convert::Infallible;
242-
fn respond_to(self, _: &'r Request<'_>) -> response::Outcome<'o, Self::Error> {
242+
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'o, Self::Error> {
243243
Response::build()
244244
.raw_header("Sec-Websocket-Version", "13")
245245
.raw_header("Sec-WebSocket-Accept", self.ws.key.clone())
@@ -252,7 +252,7 @@ impl<'r, 'o: 'r, S> Responder<'r, 'o> for MessageStream<'o, S>
252252
where S: futures::Stream<Item = Result<Message>> + Send + 'o
253253
{
254254
type Error = std::convert::Infallible;
255-
fn respond_to(self, _: &'r Request<'_>) -> response::Outcome<'o, Self::Error> {
255+
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'o, Self::Error> {
256256
Response::build()
257257
.raw_header("Sec-Websocket-Version", "13")
258258
.raw_header("Sec-WebSocket-Accept", self.ws.key.clone())

core/codegen/src/attribute/catch/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,9 @@ pub fn _catch(
8585
let catcher_response = quote_spanned!(return_type_span => {
8686
let ___responder = #user_catcher_fn_name(#(#parameter_names),*) #dot_await;
8787
match #_response::Responder::respond_to(___responder, #__req) {
88-
#Outcome::Success(v) => v,
88+
#_Ok(v) => v,
8989
// If the responder fails, we drop any typed error, and convert to 500
90-
#Outcome::Error(_) | #Outcome::Forward(_) => return Err(#Status::InternalServerError),
90+
#_Err(_) => return #_Err(#Status::InternalServerError),
9191
}
9292
});
9393

core/codegen/src/attribute/route/mod.rs

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ fn query_decls(route: &Route) -> Option<TokenStream> {
136136
fn request_guard_decl(guard: &Guard) -> TokenStream {
137137
let (ident, ty) = (guard.fn_ident.rocketized(), &guard.ty);
138138
define_spanned_export!(ty.span() =>
139-
__req, __data, _request, display_hack, FromRequest, Outcome, TypedError, resolve_error, _Box, Status
139+
__req, __data, _request, display_hack, FromRequest, Outcome, TypedError, _Box
140140
);
141141

142142
quote_spanned! { ty.span() =>
@@ -156,26 +156,23 @@ fn request_guard_decl(guard: &Guard) -> TokenStream {
156156
},
157157
#[allow(unreachable_code)]
158158
#Outcome::Error(__e) => {
159-
let __err = #resolve_error!(__e);
160-
let __err_ptr = match &__err.val {
161-
Err(r) => &r.0,
159+
let __err: #_Box<dyn #TypedError<'__r>> = #_Box::new(__e);
162160
// SAFETY: This is a pointer to __e (after moving it into a box),
163161
// so it's safe to cast it to the same type. If #ty implements
164162
// TypedError, we could downcast, but we can't write that if it doesn't.
165-
Ok(b) => unsafe { &*(b.as_ref() as *const dyn #TypedError<'_>).cast() },
166-
};
163+
let __err_ptr: &<#ty as #FromRequest<'__r>>::Error
164+
= unsafe { &*(__err.as_ref() as *const dyn #TypedError<'_>).cast() };
167165
::rocket::trace::info!(
168166
name: "failure",
169167
target: concat!("rocket::codegen::route::", module_path!()),
170168
parameter = stringify!(#ident),
171169
type_name = stringify!(#ty),
172170
reason = %#display_hack!(__err_ptr),
173-
error_type = __err.name,
171+
error_type = __err.name(),
174172
"request guard failed"
175173
);
176174

177-
// TODO: Default status
178-
return #Outcome::Error(__err.val.unwrap_or_else(|_| #_Box::new(#Status::InternalServerError)));
175+
return #Outcome::Error(__err);
179176
}
180177
};
181178
}
@@ -298,7 +295,6 @@ fn data_guard_decl(guard: &Guard) -> TokenStream {
298295
"data guard failed"
299296
);
300297

301-
// TODO: default status
302298
return #Outcome::Error(__e.val.unwrap_or_else(|_| #_Box::new(#Status::UnprocessableEntity)));
303299
}
304300
};

core/codegen/src/derive/responder.rs

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ pub fn derive_responder(input: proc_macro::TokenStream) -> TokenStream {
7777
.inner_mapper(MapperBuild::new()
7878
.with_output(|_, output| quote! {
7979
fn respond_to(self, __req: &'r #Request<'_>)
80-
-> #_response::Outcome<'o, Self::Error>
80+
-> #_response::Result<'o, Self::Error>
8181
{
8282
#output
8383
}
@@ -106,9 +106,9 @@ pub fn derive_responder(input: proc_macro::TokenStream) -> TokenStream {
106106
let mut __res = match <#ty as #_response::Responder>::respond_to(
107107
#accessor, __req
108108
) {
109-
#Outcome::Success(val) => val,
110-
#Outcome::Error(e) => return #Outcome::Error(#error_outcome),
111-
#Outcome::Forward(f) => return #Outcome::Forward(f),
109+
#_Result::Ok(val) => val,
110+
#_Result::Err(e) => return #_Result::Err(#error_outcome),
111+
// #Outcome::Forward(f) => return #Outcome::Forward(f),
112112
};
113113
}
114114
}).expect("have at least one field");
@@ -133,7 +133,7 @@ pub fn derive_responder(input: proc_macro::TokenStream) -> TokenStream {
133133
#(#headers)*
134134
#content_type
135135
#status
136-
#Outcome::Success(__res)
136+
#_Ok(__res)
137137
})
138138
})
139139
)
@@ -205,6 +205,10 @@ pub fn derive_responder(input: proc_macro::TokenStream) -> TokenStream {
205205
#i: #_catcher::Transient,
206206
<#i as #_catcher::Transient>::Transience: #_catcher::CanTranscendTo<#_catcher::Inv<'r>>,
207207
});
208+
let debug_bounds = type_params.iter()
209+
.map(|i| quote! {
210+
#i: ::std::fmt::Debug,
211+
});
208212
quote!{
209213
pub enum #name<'r, #(#type_params,)*> {
210214
#(#variants_decl)*
@@ -230,6 +234,18 @@ pub fn derive_responder(input: proc_macro::TokenStream) -> TokenStream {
230234
type Transience = ::rocket::catcher::Inv<'r>;
231235
}
232236

237+
impl<'r, #(#type_params,)*> ::std::fmt::Debug
238+
for #name<'r, #(#type_params,)*>
239+
where #(#debug_bounds)*
240+
{
241+
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
242+
match self {
243+
#(Self::#type_params(v) => v.fmt(f),)*
244+
Self::UnusedVariant(f, ..) => match *f { }
245+
}
246+
}
247+
}
248+
233249
impl<'r, #(#type_params,)*> #TypedError<'r>
234250
for #name<'r, #(#type_params,)*>
235251
where #(#error_bounds)*

core/codegen/src/lib.rs

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -320,10 +320,9 @@ route_attribute!(options => Method::Options);
320320
/// SINGLE_PARAM := '<' IDENT '>'
321321
/// ```
322322
///
323-
/// TODO: typed: docs (links)
324323
/// # Typing Requirements
325324
///
326-
/// The type of the `error` arguement must be a reference to a type that implements `TypedError`. See
325+
/// The type of the `error` arguement must be a reference to a type that implements [`TypedError`]. See
327326
/// [Typed catchers](Self#Typed-catchers) for more info.
328327
///
329328
/// All other arguments must implement [`FromError`], (or [`FromRequest`]).
@@ -336,26 +335,24 @@ route_attribute!(options => Method::Options);
336335
/// error types. This is accomplished using the [`TypedError`] trait.
337336
/// When a [`FromRequest`], [`FromParam`],
338337
/// [`FromSegments`], [`FromForm`], or [`FromData`] implementation fails or
339-
/// forwards, Rocket will convert to the error type to `dyn TypedError`, if the
340-
/// error type implements `TypedError`.
338+
/// forwards, Rocket will convert to the error type to [`dyn TypedError`], if the
339+
/// error type implements [`TypedError`].
341340
///
342341
/// Only a single error type can be carried by a request - if a route forwards,
343342
/// and another route is attempted, any error produced by the second route
344343
/// overwrites the first.
345344
///
346345
/// There are two convient types - [`FromParam`] types actually generate a
347346
/// [`FromParamError<T>`] (although you can still catch the inner `T` type).
348-
/// Likewise [`FromSegements`] actually generates [`FromSegementsError<T>`].
347+
/// Likewise [`FromSegments`] actually generates [`FromSegmentsError<T>`].
349348
///
350349
/// ## Custom error types
351350
///
352-
/// All[^transient-impls] error types that Rocket itself produces implement
351+
/// All error types that Rocket itself produces implement
353352
/// [`TypedError`], and can therefore be caught by a typed catcher. If you have
354353
/// a custom guard of any type, you can implement [`TypedError`] using the derive
355354
/// macro.
356355
///
357-
/// [^transient-impls]: As of writing, this is a WIP.
358-
///
359356
/// # Semantics
360357
///
361358
/// The attribute generates two items:
@@ -382,7 +379,15 @@ route_attribute!(options => Method::Options);
382379
/// [`Catcher`]: ../rocket/struct.Catcher.html
383380
/// [`Response`]: ../rocket/struct.Response.html
384381
/// [`Responder`]: ../rocket/response/trait.Responder.html
382+
/// [`FromError`]: ../rocket/catcher/trait.FromError.html
385383
/// [`FromRequest`]: ../rocket/request/trait.FromRequest.html
384+
/// [`FromParam`]: ../rocket/request/trait.FromParam.html
385+
/// [`FromSegments`]: ../rocket/request/trait.FromSegments.html
386+
/// [`FromData`]: ../rocket/data/trait.FromData.html
387+
/// [`TypedError`]: ../rocket/catcher/trait.TypedError.html
388+
/// [`dyn TypedError`]: ../rocket/catcher/trait.TypedError.html
389+
/// [`FromParamError<T>`]: ../rocket/request/struct.FromParamError.html
390+
/// [`FromSegmentsError<T>`]: ../rocket/request/struct.FromSegmentsError.html
386391
#[proc_macro_attribute]
387392
pub fn catch(args: TokenStream, input: TokenStream) -> TokenStream {
388393
emit!(attribute::catch::catch_attribute(args, input))
@@ -470,7 +475,7 @@ pub fn async_test(args: TokenStream, input: TokenStream) -> TokenStream {
470475
/// }
471476
/// ```
472477
///
473-
/// For all other cases, use [`#[launch]`](launch) instead.
478+
/// For all other cases, use [`#[launch]`](macro@launch) instead.
474479
///
475480
/// The function attributed with `#[rocket::main]` _must_ be `async` and _must_
476481
/// be called `main`. Violation of either results in a compile-time error.

core/http/src/status.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::fmt;
1+
use std::{convert::Infallible, fmt};
22

33
use transient::Static;
44

@@ -128,6 +128,12 @@ impl Default for Status {
128128
}
129129
}
130130

131+
impl From<Infallible> for Status {
132+
fn from(v: Infallible) -> Self {
133+
match v {}
134+
}
135+
}
136+
131137
macro_rules! ctrs {
132138
($($code:expr, $code_str:expr, $name:ident => $reason:expr),+) => {
133139
$(

core/lib/src/catcher/catcher.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -153,18 +153,18 @@ impl Catcher {
153153
/// -> BoxFuture<'r>
154154
/// {
155155
/// let res = (status, format!("404: {}", req.uri()));
156-
/// Box::pin(async move { res.respond_to(req).responder_error() })
156+
/// Box::pin(async move { res.respond_to(req).map_err(|e| e.into()) })
157157
/// }
158158
///
159159
/// fn handle_500<'r>(_: Status, req: &'r Request<'_>, _e: Option<&'r dyn TypedError<'r>>) -> BoxFuture<'r> {
160-
/// Box::pin(async move{ "Whoops, we messed up!".respond_to(req).responder_error() })
160+
/// Box::pin(async move{ "Whoops, we messed up!".respond_to(req).map_err(|e| e.into()) })
161161
/// }
162162
///
163163
/// fn handle_default<'r>(status: Status, req: &'r Request<'_>, _e: Option<&'r dyn TypedError<'r>>)
164164
/// -> BoxFuture<'r>
165165
/// {
166166
/// let res = (status, format!("{}: {}", status, req.uri()));
167-
/// Box::pin(async move { res.respond_to(req).responder_error() })
167+
/// Box::pin(async move { res.respond_to(req).map_err(|e| e.into()) })
168168
/// }
169169
///
170170
/// let not_found_catcher = Catcher::new(404, handle_404);
@@ -210,7 +210,7 @@ impl Catcher {
210210
/// -> BoxFuture<'r>
211211
/// {
212212
/// let res = (status, format!("404: {}", req.uri()));
213-
/// Box::pin(async move { res.respond_to(req).responder_error() })
213+
/// Box::pin(async move { res.respond_to(req).map_err(|e| e.into()) })
214214
/// }
215215
///
216216
/// let catcher = Catcher::new(404, handle_404);
@@ -239,7 +239,7 @@ impl Catcher {
239239
/// -> BoxFuture<'r>
240240
/// {
241241
/// let res = (status, format!("404: {}", req.uri()));
242-
/// Box::pin(async move { res.respond_to(req).responder_error() })
242+
/// Box::pin(async move { res.respond_to(req).map_err(|e| e.into()) })
243243
/// }
244244
///
245245
/// let catcher = Catcher::new(404, handle_404);
@@ -294,7 +294,7 @@ impl Catcher {
294294
/// -> BoxFuture<'r>
295295
/// {
296296
/// let res = (status, format!("404: {}", req.uri()));
297-
/// Box::pin(async move { res.respond_to(req).responder_error() })
297+
/// Box::pin(async move { res.respond_to(req).map_err(|e| e.into()) })
298298
/// }
299299
///
300300
/// let catcher = Catcher::new(404, handle_404);

0 commit comments

Comments
 (0)