Skip to content

Commit

Permalink
Rename 'Outcome::Failure' to 'Outcome::Error'.
Browse files Browse the repository at this point in the history
The primary motivation is to deconflate the leading `F`s in `Failure` and
`Forward`. In particular, when using a generics, we used `F` for forward, which
could easily be confused for `F` for `Failure`. This resolves the conflation.
  • Loading branch information
SergioBenitez committed Oct 31, 2023
1 parent 11c9c3c commit c908120
Show file tree
Hide file tree
Showing 35 changed files with 222 additions and 221 deletions.
2 changes: 1 addition & 1 deletion contrib/db_pools/codegen/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ pub fn derive_database(input: TokenStream) -> TokenStream {
) -> rocket::request::Outcome<Self, Self::Error> {
match #db_ty::fetch(req.rocket()) {
Some(db) => rocket::outcome::Outcome::Success(db),
None => rocket::outcome::Outcome::Failure((
None => rocket::outcome::Outcome::Error((
rocket::http::Status::InternalServerError, ()))
}
}
Expand Down
6 changes: 3 additions & 3 deletions contrib/db_pools/lib/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ pub struct Initializer<D: Database>(Option<&'static str>, PhantomData<fn() -> D>
/// [`connect_timeout`](crate::Config::connect_timeout) seconds.
/// * If the `Initializer` fairing was _not_ attached, the guard _fails_ with
/// status `InternalServerError`. A [`Sentinel`] guards this condition, and so
/// this type of failure is unlikely to occur. A `None` error is returned.
/// this type of error is unlikely to occur. A `None` error is returned.
/// * If a connection is not available within `connect_timeout` seconds or
/// another error occurs, the guard _fails_ with status `ServiceUnavailable`
/// and the error is returned in `Some`.
Expand Down Expand Up @@ -288,9 +288,9 @@ impl<'r, D: Database> FromRequest<'r> for Connection<D> {
match D::fetch(req.rocket()) {
Some(db) => match db.get().await {
Ok(conn) => Outcome::Success(Connection(conn)),
Err(e) => Outcome::Failure((Status::ServiceUnavailable, Some(e))),
Err(e) => Outcome::Error((Status::ServiceUnavailable, Some(e))),
},
None => Outcome::Failure((Status::InternalServerError, None)),
None => Outcome::Error((Status::InternalServerError, None)),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion contrib/dyn_templates/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ impl<'r> FromRequest<'r> for Metadata<'r> {
error_!("Uninitialized template context: missing fairing.");
info_!("To use templates, you must attach `Template::fairing()`.");
info_!("See the `Template` documentation for more information.");
request::Outcome::Failure((Status::InternalServerError, ()))
request::Outcome::Error((Status::InternalServerError, ()))
})
}
}
2 changes: 1 addition & 1 deletion contrib/sync_db_pools/lib/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ impl<'r, K: 'static, C: Poolable> FromRequest<'r> for Connection<K, C> {
Some(c) => c.get().await.into_outcome((Status::ServiceUnavailable, ())),
None => {
error_!("Missing database fairing for `{}`", std::any::type_name::<K>());
Outcome::Failure((Status::InternalServerError, ()))
Outcome::Error((Status::InternalServerError, ()))
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions core/codegen/src/attribute/route/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,9 @@ fn request_guard_decl(guard: &Guard) -> TokenStream {
#_log::warn_!("Request guard `{}` is forwarding.", stringify!(#ty));
return #Outcome::Forward((#__data, __e));
},
#Outcome::Failure((__c, __e)) => {
#Outcome::Error((__c, __e)) => {
#_log::warn_!("Request guard `{}` failed: {:?}.", stringify!(#ty), __e);
return #Outcome::Failure(__c);
return #Outcome::Error(__c);
}
};
}
Expand Down Expand Up @@ -189,9 +189,9 @@ fn data_guard_decl(guard: &Guard) -> TokenStream {
#_log::warn_!("Data guard `{}` is forwarding.", stringify!(#ty));
return #Outcome::Forward((__d, __e));
}
#Outcome::Failure((__c, __e)) => {
#Outcome::Error((__c, __e)) => {
#_log::warn_!("Data guard `{}` failed: {:?}.", stringify!(#ty), __e);
return #Outcome::Failure(__c);
return #Outcome::Error(__c);
}
};
}
Expand Down
7 changes: 3 additions & 4 deletions core/codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,7 @@ macro_rules! route_attribute {
///
/// If a request guard fails, the request is forwarded if the
/// [`Outcome`] is `Forward` or failed if the [`Outcome`] is
/// `Failure`. See [`FromRequest` Outcomes] for further
/// detail.
/// `Error`. See [`FromRequest` Outcomes] for further detail.
///
/// 2. Path and query guards in an unspecified order. If a path
/// or query guard fails, the request is forwarded.
Expand All @@ -249,7 +248,7 @@ macro_rules! route_attribute {
///
/// If a data guard fails, the request is forwarded if the
/// [`Outcome`] is `Forward` or failed if the [`Outcome`] is
/// `Failure`. See [`FromData`] for further detail.
/// `Error`. See [`FromData`] for further detail.
///
/// If all validation succeeds, the decorated function is called.
/// The returned value is used to generate a [`Response`] via the
Expand Down Expand Up @@ -448,7 +447,7 @@ pub fn main(args: TokenStream, input: TokenStream) -> TokenStream {
/// #[rocket::main]
/// async fn main() {
/// // Recall that an uninspected `Error` will cause a pretty-printed panic,
/// // so rest assured failures do not go undetected when using `#[launch]`.
/// // so rest assured errors do not go undetected when using `#[launch]`.
/// let _ = rocket().launch().await;
/// }
/// ```
Expand Down
4 changes: 2 additions & 2 deletions core/http/src/parse/uri/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ macro_rules! assert_parse_eq {
match from_str($from) {
Ok(output) => {
if output != expected {
println!("Failure on: {:?}", $from);
println!("Error on: {:?}", $from);
assert_eq!(output, expected, "{} != {}", output, expected);
}
}
Expand Down Expand Up @@ -53,7 +53,7 @@ macro_rules! assert_displays_eq {
Ok(output) => {
let output_string = output.to_string();
if output_string != string {
println!("Failure on: {:?}", $string);
println!("Error on: {:?}", $string);
println!("Got: {:?}", output_string);
println!("Parsed as: {:?}", output);
panic!("failed");
Expand Down
2 changes: 1 addition & 1 deletion core/http/src/tls/mtls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,7 @@ impl fmt::Display for Name<'_> {
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Parse(e) => write!(f, "parse failure: {}", e),
Error::Parse(e) => write!(f, "parse error: {}", e),
Error::Incomplete(_) => write!(f, "incomplete certificate data"),
Error::Trailing(n) => write!(f, "found {} trailing bytes", n),
Error::Empty => write!(f, "empty certificate chain"),
Expand Down
12 changes: 7 additions & 5 deletions core/lib/src/catcher/catcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@ use yansi::Paint;
///
/// * A failing guard.
/// * A failing responder.
/// * A forwarding guard.
/// * Routing failure.
///
/// Each failure is paired with a status code. Guards and responders indicate
/// the status code themselves via their `Err` return value while a routing
/// failure is always a `404`. Rocket invokes the error handler for the catcher
/// with the error's status code.
/// 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
///
Expand All @@ -33,7 +35,7 @@ use yansi::Paint;
///
/// # Routing
///
/// If a route fails by returning a failure [`Outcome`], Rocket routes the
/// 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
Expand Down
2 changes: 1 addition & 1 deletion core/lib/src/config/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ impl Config {
///
/// # Panics
///
/// If extraction fails, prints an error message indicating the failure and
/// If extraction fails, prints an error message indicating the error and
/// panics. For a version that doesn't panic, use [`Config::try_from()`].
///
/// # Example
Expand Down
4 changes: 2 additions & 2 deletions core/lib/src/config/secret_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ enum Kind {
/// ```
///
/// When running in any other profile with the `secrets` feature enabled,
/// providing a key of `0` or not provided a key at all results in a failure at
/// providing a key of `0` or not provided a key at all results in an error at
/// launch-time:
///
/// ```rust
Expand All @@ -67,7 +67,7 @@ enum Kind {
/// .select(profile.clone());
///
/// let rocket = rocket::custom(figment);
/// let error = Client::tracked(rocket).expect_err("failure in non-debug");
/// let error = Client::tracked(rocket).expect_err("error in non-debug");
/// assert!(matches!(error.kind(), ErrorKind::InsecureSecretKey(profile)));
/// ```
///
Expand Down
4 changes: 2 additions & 2 deletions core/lib/src/data/capped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,10 +260,10 @@ macro_rules! impl_strict_from_data_from_capped {
Success(p) if p.is_complete() => Success(p.into_inner()),
Success(_) => {
let e = Error::new(UnexpectedEof, "data limit exceeded");
Failure((Status::BadRequest, e.into()))
Error((Status::BadRequest, e.into()))
},
Forward(d) => Forward(d),
Failure((s, e)) => Failure((s, e)),
Error((s, e)) => Error((s, e)),
}
}
}
Expand Down
24 changes: 12 additions & 12 deletions core/lib/src/data/from_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ pub type Outcome<'r, T, E = <T as FromData<'r>>::Error>
= outcome::Outcome<T, (Status, E), (Data<'r>, Status)>;

impl<'r, S, E> IntoOutcome<S, (Status, E), (Data<'r>, Status)> for Result<S, E> {
type Failure = Status;
type Error = Status;
type Forward = (Data<'r>, Status);

#[inline]
fn into_outcome(self, status: Status) -> Outcome<'r, S, E> {
match self {
Ok(val) => Success(val),
Err(err) => Failure((status, err))
Err(err) => Error((status, err))
}
}

Expand Down Expand Up @@ -251,6 +251,7 @@ impl<'r, S, E> IntoOutcome<S, (Status, E), (Data<'r>, Status)> for Result<S, E>
/// use rocket::request::{self, Request};
/// use rocket::data::{self, Data, FromData, ToByteUnit};
/// use rocket::http::{Status, ContentType};
/// use rocket::outcome::Outcome;
///
/// #[derive(Debug)]
/// enum Error {
Expand All @@ -266,12 +267,11 @@ impl<'r, S, E> IntoOutcome<S, (Status, E), (Data<'r>, Status)> for Result<S, E>
///
/// async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> data::Outcome<'r, Self> {
/// use Error::*;
/// use rocket::outcome::Outcome::*;
///
/// // Ensure the content type is correct before opening the data.
/// let person_ct = ContentType::new("application", "x-person");
/// if req.content_type() != Some(&person_ct) {
/// return Forward((data, Status::NotFound));
/// return Outcome::Forward((data, Status::NotFound));
/// }
///
/// // Use a configured limit with name 'person' or fallback to default.
Expand All @@ -280,8 +280,8 @@ impl<'r, S, E> IntoOutcome<S, (Status, E), (Data<'r>, Status)> for Result<S, E>
/// // Read the data into a string.
/// let string = match data.open(limit).into_string().await {
/// Ok(string) if string.is_complete() => string.into_inner(),
/// Ok(_) => return Failure((Status::PayloadTooLarge, TooLarge)),
/// Err(e) => return Failure((Status::InternalServerError, Io(e))),
/// Ok(_) => return Outcome::Error((Status::PayloadTooLarge, TooLarge)),
/// Err(e) => return Outcome::Error((Status::InternalServerError, Io(e))),
/// };
///
/// // We store `string` in request-local cache for long-lived borrows.
Expand All @@ -290,16 +290,16 @@ impl<'r, S, E> IntoOutcome<S, (Status, E), (Data<'r>, Status)> for Result<S, E>
/// // Split the string into two pieces at ':'.
/// let (name, age) = match string.find(':') {
/// Some(i) => (&string[..i], &string[(i + 1)..]),
/// None => return Failure((Status::UnprocessableEntity, NoColon)),
/// None => return Outcome::Error((Status::UnprocessableEntity, NoColon)),
/// };
///
/// // Parse the age.
/// let age: u16 = match age.parse() {
/// Ok(age) => age,
/// Err(_) => return Failure((Status::UnprocessableEntity, InvalidAge)),
/// Err(_) => return Outcome::Error((Status::UnprocessableEntity, InvalidAge)),
/// };
///
/// Success(Person { name, age })
/// Outcome::Success(Person { name, age })
/// }
/// }
///
Expand Down Expand Up @@ -331,7 +331,7 @@ pub trait FromData<'r>: Sized {
///
/// If validation and parsing succeeds, an outcome of `Success` is returned.
/// If the data is not appropriate given the type of `Self`, `Forward` is
/// returned. If parsing fails, `Failure` is returned.
/// returned. If parsing fails, `Error` is returned.
async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> Outcome<'r, Self>;
}

Expand Down Expand Up @@ -428,7 +428,7 @@ impl<'r, T: FromData<'r> + 'r> FromData<'r> for Result<T, T::Error> {
async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> Outcome<'r, Self> {
match T::from_data(req, data).await {
Success(v) => Success(Ok(v)),
Failure((_, e)) => Success(Err(e)),
Error((_, e)) => Success(Err(e)),
Forward(d) => Forward(d),
}
}
Expand All @@ -441,7 +441,7 @@ impl<'r, T: FromData<'r>> FromData<'r> for Option<T> {
async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> Outcome<'r, Self> {
match T::from_data(req, data).await {
Success(v) => Success(Some(v)),
Failure(..) | Forward(..) => Success(None),
Error(..) | Forward(..) => Success(None),
}
}
}
4 changes: 2 additions & 2 deletions core/lib/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,9 +216,9 @@ impl Error {
crate::config::pretty_print_error(error.clone());
"aborting due to invalid configuration"
}
ErrorKind::SentinelAborts(ref failures) => {
ErrorKind::SentinelAborts(ref errors) => {
error!("Rocket failed to launch due to aborting sentinels:");
for sentry in failures {
for sentry in errors {
let name = sentry.type_name.primary().bold();
let (file, line, col) = sentry.location;
info_!("{} ({}:{}:{})", name, file, line, col);
Expand Down
6 changes: 3 additions & 3 deletions core/lib/src/fairing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub type Result<T = Rocket<Build>, E = Rocket<Build>> = std::result::Result<T, E

// We might imagine that a request fairing returns an `Outcome`. If it returns
// `Success`, we don't do any routing and use that response directly. Same if it
// returns `Failure`. We only route if it returns `Forward`. I've chosen not to
// returns `Error`. We only route if it returns `Forward`. I've chosen not to
// go this direction because I feel like request guards are the correct
// mechanism to use here. In other words, enabling this at the fairing level
// encourages implicit handling, a bad practice. Fairings can still, however,
Expand Down Expand Up @@ -125,7 +125,7 @@ pub type Result<T = Rocket<Build>, E = Rocket<Build>> = std::result::Result<T, E
/// recursively attaching ignite fairings. It returns `Ok` if it would like
/// ignition and launch to proceed nominally and `Err` otherwise. If an
/// ignite fairing returns `Err`, launch will be aborted. All ignite
/// fairings are executed even if one or more signal a failure.
/// fairings are executed even if one or more signal an error.
///
/// * **<a name="liftoff">Liftoff</a> (`on_liftoff`)**
///
Expand Down Expand Up @@ -417,7 +417,7 @@ pub type Result<T = Rocket<Build>, E = Rocket<Build>> = std::result::Result<T, E
/// async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, ()> {
/// match *request.local_cache(|| TimerStart(None)) {
/// TimerStart(Some(time)) => request::Outcome::Success(StartTime(time)),
/// TimerStart(None) => request::Outcome::Failure((Status::InternalServerError, ())),
/// TimerStart(None) => request::Outcome::Error((Status::InternalServerError, ())),
/// }
/// }
/// }
Expand Down
2 changes: 1 addition & 1 deletion core/lib/src/form/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ impl<'v> Errors<'v> {
/// Returns the highest [`Error::status()`] of all of the errors in `self`
/// or [`Status::InternalServerError`] if `self` is empty. This is the
/// status that is set by the [`Form`](crate::form::Form) data guard on
/// failure.
/// error.
///
/// See [`Error::status()`] for the corresponding status code of each
/// [`Error`] variant.
Expand Down
6 changes: 3 additions & 3 deletions core/lib/src/form/form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ use crate::form::prelude::*;
///
/// If the request `ContentType` _does_ identify as a form but the form data
/// does not parse as `T`, according to `T`'s [`FromForm`] implementation, the
/// guard **fails**. The `Failure` variant contains of the [`Errors`] emitted by
/// `T`'s `FromForm` parser. If the error is not caught by a
/// guard **fails**. The `Error` variant contains a vector of the [`Errors`]
/// emitted by `T`'s `FromForm` parser. If the error is not caught by a
/// [`form::Result<T>`](Result) or `Option<Form<T>>` data guard, the status code
/// is set to [`Errors::status()`], and the corresponding error catcher is
/// called.
Expand Down Expand Up @@ -334,7 +334,7 @@ impl<'r, T: FromForm<'r>> FromData<'r> for Form<T> {

match T::finalize(context) {
Ok(value) => Outcome::Success(Form(value)),
Err(e) => Outcome::Failure((e.status(), e)),
Err(e) => Outcome::Error((e.status(), e)),
}
}
}
6 changes: 3 additions & 3 deletions core/lib/src/form/from_form_field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ impl<'v> FromFormField<'v> for Capped<&'v str> {

match <Capped<&'v str> as FromData>::from_data(f.request, f.data).await {
Outcome::Success(p) => Ok(p),
Outcome::Failure((_, e)) => Err(e)?,
Outcome::Error((_, e)) => Err(e)?,
Outcome::Forward(..) => {
Err(Error::from(ErrorKind::Unexpected).with_entity(Entity::DataField))?
}
Expand All @@ -318,7 +318,7 @@ impl<'v> FromFormField<'v> for Capped<String> {

match <Capped<String> as FromData>::from_data(f.request, f.data).await {
Outcome::Success(p) => Ok(p),
Outcome::Failure((_, e)) => Err(e)?,
Outcome::Error((_, e)) => Err(e)?,
Outcome::Forward(..) => {
Err(Error::from(ErrorKind::Unexpected).with_entity(Entity::DataField))?
}
Expand Down Expand Up @@ -354,7 +354,7 @@ impl<'v> FromFormField<'v> for Capped<&'v [u8]> {

match <Capped<&'v [u8]> as FromData>::from_data(f.request, f.data).await {
Outcome::Success(p) => Ok(p),
Outcome::Failure((_, e)) => Err(e)?,
Outcome::Error((_, e)) => Err(e)?,
Outcome::Forward(..) => {
Err(Error::from(ErrorKind::Unexpected).with_entity(Entity::DataField))?
}
Expand Down
2 changes: 1 addition & 1 deletion core/lib/src/form/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl<'r, 'i> Parser<'r, 'i> {

match parser {
Ok(storage) => Outcome::Success(storage),
Err(e) => Outcome::Failure((e.status(), e.into()))
Err(e) => Outcome::Error((e.status(), e.into()))
}
}

Expand Down
Loading

0 comments on commit c908120

Please sign in to comment.