Return a `LaunchError` from `launch` when launching fails.

This is a (minor) breaking change. If `rocket.launch()` is the last expression
in a function, the return type will change from `()` to `LaunchError`. A simple
workaround that preserves the previous functionality is to simply add a
semicolon after `launch()`: `rocket.launch();`.

resolves #34
This commit is contained in:
Sergio Benitez 2017-03-15 22:10:09 -07:00
parent da157a061d
commit 65da988962
18 changed files with 199 additions and 32 deletions

View File

@ -6,5 +6,5 @@ extern crate config;
// This example's illustration is the Rocket.toml file.
fn main() {
rocket::ignite().mount("/hello", routes![config::hello]).launch()
rocket::ignite().mount("/hello", routes![config::hello]).launch();
}

View File

@ -37,5 +37,5 @@ fn index(cookies: Cookies) -> Template {
}
fn main() {
rocket::ignite().mount("/", routes![submit, index]).launch()
rocket::ignite().mount("/", routes![submit, index]).launch();
}

View File

@ -20,8 +20,11 @@ fn not_found(req: &rocket::Request) -> content::HTML<String> {
}
fn main() {
rocket::ignite()
let e = rocket::ignite()
.mount("/", routes![hello])
.catch(errors![not_found])
.launch();
println!("Whoops! Rocket didn't launch!");
println!("This went wrong: {}", e);
}

View File

@ -85,5 +85,5 @@ fn rocket() -> rocket::Rocket {
}
fn main() {
rocket().launch()
rocket().launch();
}

View File

@ -48,5 +48,5 @@ fn rocket() -> rocket::Rocket {
}
fn main() {
rocket().launch()
rocket().launch();
}

View File

@ -29,7 +29,7 @@ fn header_count(header_count: HeaderCount) -> String {
}
fn main() {
rocket::ignite().mount("/", routes![header_count]).launch()
rocket::ignite().mount("/", routes![header_count]).launch();
}
#[cfg(test)]

View File

@ -26,5 +26,5 @@ fn login() -> &'static str {
}
fn main() {
rocket::ignite().mount("/", routes![root, user, login]).launch()
rocket::ignite().mount("/", routes![root, user, login]).launch();
}

View File

@ -53,5 +53,5 @@ fn index() -> &'static str {
}
fn main() {
rocket::ignite().mount("/", routes![index, upload, retrieve]).launch()
rocket::ignite().mount("/", routes![index, upload, retrieve]).launch();
}

View File

@ -21,5 +21,5 @@ fn hello(person: Person) -> String {
}
fn main() {
rocket::ignite().mount("/", routes![hello]).launch()
rocket::ignite().mount("/", routes![hello]).launch();
}

View File

@ -83,5 +83,5 @@ fn index() -> Redirect {
fn main() {
rocket::ignite()
.mount("/", routes![index, user_index, login, logout, login_user, login_page])
.launch()
.launch();
}

View File

@ -9,7 +9,7 @@ fn hello() -> &'static str {
}
fn main() {
rocket::ignite().mount("/", routes![hello]).launch()
rocket::ignite().mount("/", routes![hello]).launch();
}
#[cfg(test)]

View File

@ -55,7 +55,7 @@ use term_painter::Color::*;
///
/// fn main() {
/// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite().catch(errors![internal_error, not_found]).launch()
/// rocket::ignite().catch(errors![internal_error, not_found]).launch();
/// # }
/// }
/// ```

View File

@ -1,3 +1,10 @@
//! Types representing various errors that can occur in a Rocket application.
use std::{io, fmt};
use std::sync::atomic::{Ordering, AtomicBool};
use http::hyper;
/// [unstable] Error type for Rocket. Likely to change.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Error {
@ -12,3 +19,154 @@ pub enum Error {
/// The requested key/index does not exist.
NoKey,
}
/// The kind of launch error that occured.
///
/// In almost every instance, a launch error occurs because of an I/O error;
/// this represented by the `Io` variant. The `Unknown` variant captures all
/// other kinds of launch errors.
#[derive(Debug)]
pub enum LaunchErrorKind {
Io(io::Error),
Unknown(Box<::std::error::Error + Send + Sync>)
}
/// An error that occurred during launch.
///
/// A `LaunchError` is returned by
/// [rocket::launch](/rocket/struct.Rocket.html#method.launch) when launching an
/// application fails for some reason.
///
/// # Panics
///
/// A value of this type panics if it is dropped without first being inspected.
/// An _inspection_ occurs when any method is called. For instance, if
/// `println!("Error: {}", e)` is called, where `e: LaunchError`, the
/// `Display::fmt` method being called by `println!` results in `e` being marked
/// as inspected; a subsequent `drop` of the value will _not_ result in a panic.
/// The following snippet illustrates this:
///
/// ```rust
/// # if false {
/// let error = rocket::ignite().launch();
///
/// // This line is only reached if launching failed. This "inspects" the error.
/// println!("Launch failed! Error: {}", error);
///
/// // This call to drop (explicit here for demonstration) will do nothing.
/// drop(error);
/// # }
/// ```
///
/// When a value of this type panics, the corresponding error message is pretty
/// printed to the console. The following snippet illustrates this:
///
/// ```rust
/// # if false {
/// let error = rocket::ignite().launch();
///
/// // This call to drop (explicit here for demonstration) will result in
/// // `error` being pretty-printed to the console along with a `panic!`.
/// drop(error);
/// # }
/// ```
pub struct LaunchError {
handled: AtomicBool,
kind: LaunchErrorKind
}
impl LaunchError {
#[inline(always)]
fn new(kind: LaunchErrorKind) -> LaunchError {
LaunchError { handled: AtomicBool::new(false), kind: kind }
}
#[inline(always)]
fn was_handled(&self) -> bool {
self.handled.load(Ordering::Acquire)
}
#[inline(always)]
fn mark_handled(&self) {
self.handled.store(true, Ordering::Release)
}
/// Retrieve the `kind` of the launch error.
///
/// # Example
///
/// ```rust
/// # if false {
/// let error = rocket::ignite().launch();
///
/// // This line is only reached if launch failed.
/// let error_kind = error.kind();
/// # }
/// ```
#[inline]
pub fn kind(&self) -> &LaunchErrorKind {
self.mark_handled();
&self.kind
}
}
impl From<hyper::Error> for LaunchError {
fn from(error: hyper::Error) -> LaunchError {
match error {
hyper::Error::Io(e) => LaunchError::new(LaunchErrorKind::Io(e)),
e => LaunchError::new(LaunchErrorKind::Unknown(Box::new(e)))
}
}
}
impl fmt::Display for LaunchErrorKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
LaunchErrorKind::Io(ref e) => write!(f, "I/O error: {}", e),
LaunchErrorKind::Unknown(ref e) => write!(f, "unknown error: {}", e)
}
}
}
impl fmt::Debug for LaunchError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.mark_handled();
write!(f, "{:?}", self.kind())
}
}
impl fmt::Display for LaunchError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.mark_handled();
write!(f, "{}", self.kind())
}
}
impl ::std::error::Error for LaunchError {
fn description(&self) -> &str {
self.mark_handled();
match *self.kind() {
LaunchErrorKind::Io(_) => "an I/O error occured during launch",
LaunchErrorKind::Unknown(_) => "an unknown error occured during launch"
}
}
}
impl Drop for LaunchError {
fn drop(&mut self) {
if self.was_handled() {
return
}
match *self.kind() {
LaunchErrorKind::Io(ref e) => {
error!("Rocket failed to launch due to an I/O error.");
panic!("{}", e);
}
LaunchErrorKind::Unknown(ref e) => {
error!("Rocket failed to launch due to an unknown error.");
panic!("{}", e);
}
}
}
}

View File

@ -13,6 +13,7 @@ pub(crate) use hyper::net;
pub(crate) use hyper::method::Method;
pub(crate) use hyper::status::StatusCode;
pub(crate) use hyper::error::Error;
pub(crate) use hyper::uri::RequestUri;
pub(crate) use hyper::http::h1;
pub(crate) use hyper::buffer;

View File

@ -74,7 +74,7 @@
//!
//! fn main() {
//! # if false { // We don't actually want to launch the server in an example.
//! rocket::ignite().mount("/", routes![hello]).launch()
//! rocket::ignite().mount("/", routes![hello]).launch();
//! # }
//! }
//! ```
@ -117,8 +117,8 @@ pub mod outcome;
pub mod config;
pub mod data;
pub mod handler;
pub mod error;
mod error;
mod router;
mod rocket;
mod codegen;
@ -133,7 +133,7 @@ mod ext;
#[doc(inline)] pub use data::Data;
pub use router::Route;
pub use request::{Request, State};
pub use error::Error;
pub use error::{Error, LaunchError};
pub use catcher::Catcher;
pub use rocket::Rocket;

View File

@ -46,7 +46,7 @@ use http::Status;
/// rocket::ignite()
/// .mount("/", routes![index, raw_config_value])
/// .manage(config)
/// .launch()
/// .launch();
/// # }
/// }
/// ```

View File

@ -71,7 +71,7 @@ const FLASH_COOKIE_NAME: &'static str = "_flash";
///
/// fn main() {
/// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite().mount("/", routes![login, index]).launch()
/// rocket::ignite().mount("/", routes![login, index]).launch();
/// # }
/// }
/// ```

View File

@ -18,7 +18,7 @@ use response::{Body, Response};
use router::{Router, Route};
use catcher::{self, Catcher};
use outcome::Outcome;
use error::Error;
use error::{Error, LaunchError};
use http::{Method, Status, Header, Session};
use http::hyper::{self, header};
@ -391,7 +391,7 @@ impl Rocket {
/// fn main() {
/// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite().mount("/hello", routes![hi])
/// # .launch()
/// # .launch();
/// # }
/// }
/// ```
@ -411,7 +411,7 @@ impl Rocket {
///
/// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite().mount("/hello", vec![Route::new(Get, "/world", hi)])
/// # .launch()
/// # .launch();
/// # }
/// ```
pub fn mount(mut self, base: &str, routes: Vec<Route>) -> Self {
@ -459,7 +459,7 @@ impl Rocket {
/// fn main() {
/// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite().catch(errors![internal_error, not_found])
/// # .launch()
/// # .launch();
/// # }
/// }
/// ```
@ -514,7 +514,7 @@ impl Rocket {
/// rocket::ignite()
/// .mount("/", routes![index])
/// .manage(MyValue(10))
/// .launch()
/// .launch();
/// # }
/// }
/// ```
@ -530,19 +530,23 @@ impl Rocket {
/// Starts the application server and begins listening for and dispatching
/// requests to mounted routes and catchers.
///
/// # Panics
/// # Error
///
/// If the server could not be started, this method prints the reason and
/// then exits the process.
/// If there is a problem starting the application, a
/// [LaunchError](/rocket/struct.LaunchError.html) is returned. Note
/// that a value of type `LaunchError` panics if dropped without first being
/// inspected. See the [LaunchError
/// documentation](/rocket/struct.LaunchError.html) for more
/// information.
///
/// # Examples
///
/// ```rust
/// # if false {
/// rocket::ignite().launch()
/// rocket::ignite().launch();
/// # }
/// ```
pub fn launch(self) {
pub fn launch(self) -> LaunchError {
if self.router.has_collisions() {
warn!("Route collisions detected!");
}
@ -550,10 +554,7 @@ impl Rocket {
let full_addr = format!("{}:{}", self.config.address, self.config.port);
let server = match hyper::Server::http(full_addr.as_str()) {
Ok(hyper_server) => hyper_server,
Err(e) => {
error!("Failed to start server.");
panic!("{}", e);
}
Err(e) => return LaunchError::from(e)
};
info!("🚀 {} {}{}...",
@ -562,6 +563,10 @@ impl Rocket {
White.bold().paint(&full_addr));
let threads = self.config.workers as usize;
server.handle_threads(self, threads).unwrap();
if let Err(e) = server.handle_threads(self, threads) {
return LaunchError::from(e);
}
unreachable!("the call to `handle_threads` should block on success")
}
}