refactor(error): remove redundant parts of error names

The old names followed the old style of including the module name and
"Error" in each variant. The new style is to refer to an error from its
owning module, and variants are now scoped to their enum, so there's no
need to include the enum name in the variant name.

BREAKING CHANGE: The terms `Http` and `Error` have been removed from the Error
  type and its variants. `HttpError` should now be accessed as `hyper::Error`,
  and variants like `HttpIoError` should be accessed as `Error::Io`.
This commit is contained in:
Sean McArthur
2015-04-16 10:52:34 -07:00
parent c29af72972
commit 9ba074d150
11 changed files with 81 additions and 87 deletions

View File

@@ -43,8 +43,8 @@ use header::{ContentLength, Location};
use method::Method; use method::Method;
use net::{NetworkConnector, NetworkStream, HttpConnector, ContextVerifier}; use net::{NetworkConnector, NetworkStream, HttpConnector, ContextVerifier};
use status::StatusClass::Redirection; use status::StatusClass::Redirection;
use {Url, HttpResult}; use {Url};
use HttpError::HttpUriError; use Error;
pub use self::pool::Pool; pub use self::pool::Pool;
pub use self::request::Request; pub use self::request::Request;
@@ -203,7 +203,7 @@ impl<'a, U: IntoUrl> RequestBuilder<'a, U> {
} }
/// Execute this request and receive a Response back. /// Execute this request and receive a Response back.
pub fn send(self) -> HttpResult<Response> { pub fn send(self) -> ::Result<Response> {
let RequestBuilder { client, method, url, headers, body } = self; let RequestBuilder { client, method, url, headers, body } = self;
let mut url = try!(url.into_url()); let mut url = try!(url.into_url());
trace!("send {:?} {:?}", method, url); trace!("send {:?} {:?}", method, url);
@@ -382,15 +382,15 @@ impl Default for RedirectPolicy {
} }
} }
fn get_host_and_port(url: &Url) -> HttpResult<(String, u16)> { fn get_host_and_port(url: &Url) -> ::Result<(String, u16)> {
let host = match url.serialize_host() { let host = match url.serialize_host() {
Some(host) => host, Some(host) => host,
None => return Err(HttpUriError(UrlError::EmptyHost)) None => return Err(Error::Uri(UrlError::EmptyHost))
}; };
trace!("host={:?}", host); trace!("host={:?}", host);
let port = match url.port_or_default() { let port = match url.port_or_default() {
Some(port) => port, Some(port) => port,
None => return Err(HttpUriError(UrlError::InvalidPort)) None => return Err(Error::Uri(UrlError::InvalidPort))
}; };
trace!("port={:?}", port); trace!("port={:?}", port);
Ok((host, port)) Ok((host, port))

View File

@@ -12,7 +12,6 @@ use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{self, HttpWriter, LINE_ENDING}; use http::{self, HttpWriter, LINE_ENDING};
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
use version; use version;
use HttpResult;
use client::{Response, get_host_and_port}; use client::{Response, get_host_and_port};
@@ -43,14 +42,14 @@ impl<W> Request<W> {
impl Request<Fresh> { impl Request<Fresh> {
/// Create a new client request. /// Create a new client request.
pub fn new(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> { pub fn new(method: method::Method, url: Url) -> ::Result<Request<Fresh>> {
let mut conn = HttpConnector(None); let mut conn = HttpConnector(None);
Request::with_connector(method, url, &mut conn) Request::with_connector(method, url, &mut conn)
} }
/// Create a new client request with a specific underlying NetworkStream. /// Create a new client request with a specific underlying NetworkStream.
pub fn with_connector<C, S>(method: method::Method, url: Url, connector: &mut C) pub fn with_connector<C, S>(method: method::Method, url: Url, connector: &mut C)
-> HttpResult<Request<Fresh>> where -> ::Result<Request<Fresh>> where
C: NetworkConnector<Stream=S>, C: NetworkConnector<Stream=S>,
S: Into<Box<NetworkStream + Send>> { S: Into<Box<NetworkStream + Send>> {
let (host, port) = try!(get_host_and_port(&url)); let (host, port) = try!(get_host_and_port(&url));
@@ -76,7 +75,7 @@ impl Request<Fresh> {
/// Consume a Fresh Request, writing the headers and method, /// Consume a Fresh Request, writing the headers and method,
/// returning a Streaming Request. /// returning a Streaming Request.
pub fn start(mut self) -> HttpResult<Request<Streaming>> { pub fn start(mut self) -> ::Result<Request<Streaming>> {
let mut uri = self.url.serialize_path().unwrap(); let mut uri = self.url.serialize_path().unwrap();
//TODO: this needs a test //TODO: this needs a test
if let Some(ref q) = self.url.query { if let Some(ref q) = self.url.query {
@@ -154,7 +153,7 @@ impl Request<Streaming> {
/// Completes writing the request, and returns a response to read from. /// Completes writing the request, and returns a response to read from.
/// ///
/// Consumes the Request. /// Consumes the Request.
pub fn send(self) -> HttpResult<Response> { pub fn send(self) -> ::Result<Response> {
let mut raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes let mut raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes
if !http::should_keep_alive(self.version, &self.headers) { if !http::should_keep_alive(self.version, &self.headers) {
try!(raw.close(Shutdown::Write)); try!(raw.close(Shutdown::Write));

View File

@@ -12,7 +12,6 @@ use http::{self, HttpReader, RawStatus};
use http::HttpReader::{SizedReader, ChunkedReader, EofReader}; use http::HttpReader::{SizedReader, ChunkedReader, EofReader};
use status; use status;
use version; use version;
use HttpResult;
/// A response for a client request to a remote server. /// A response for a client request to a remote server.
#[derive(Debug)] #[derive(Debug)]
@@ -32,7 +31,7 @@ pub struct Response<S = HttpStream> {
impl Response { impl Response {
/// Creates a new response from a server. /// Creates a new response from a server.
pub fn new(stream: Box<NetworkStream + Send>) -> HttpResult<Response> { pub fn new(stream: Box<NetworkStream + Send>) -> ::Result<Response> {
let mut stream = BufReader::new(stream); let mut stream = BufReader::new(stream);
let head = try!(http::parse_response(&mut stream)); let head = try!(http::parse_response(&mut stream));

View File

@@ -1,88 +1,88 @@
//! HttpError and HttpResult module. //! Error and Result module.
use std::error::Error; use std::error::Error as StdError;
use std::fmt; use std::fmt;
use std::io::Error as IoError; use std::io::Error as IoError;
use httparse; use httparse;
use url; use url;
use self::HttpError::{HttpMethodError, HttpUriError, HttpVersionError, use self::Error::{Method, Uri, Version,
HttpHeaderError, HttpStatusError, HttpIoError, Header, Status, Io,
HttpTooLargeError}; TooLarge};
/// Result type often returned from methods that can have `HttpError`s. /// Result type often returned from methods that can have hyper `Error`s.
pub type HttpResult<T> = Result<T, HttpError>; pub type Result<T> = ::std::result::Result<T, Error>;
/// A set of errors that can occur parsing HTTP streams. /// A set of errors that can occur parsing HTTP streams.
#[derive(Debug)] #[derive(Debug)]
pub enum HttpError { pub enum Error {
/// An invalid `Method`, such as `GE,T`. /// An invalid `Method`, such as `GE,T`.
HttpMethodError, Method,
/// An invalid `RequestUri`, such as `exam ple.domain`. /// An invalid `RequestUri`, such as `exam ple.domain`.
HttpUriError(url::ParseError), Uri(url::ParseError),
/// An invalid `HttpVersion`, such as `HTP/1.1` /// An invalid `HttpVersion`, such as `HTP/1.1`
HttpVersionError, Version,
/// An invalid `Header`. /// An invalid `Header`.
HttpHeaderError, Header,
/// A message head is too large to be reasonable. /// A message head is too large to be reasonable.
HttpTooLargeError, TooLarge,
/// An invalid `Status`, such as `1337 ELITE`. /// An invalid `Status`, such as `1337 ELITE`.
HttpStatusError, Status,
/// An `IoError` that occured while trying to read or write to a network stream. /// An `IoError` that occured while trying to read or write to a network stream.
HttpIoError(IoError), Io(IoError),
} }
impl fmt::Display for HttpError { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.description()) f.write_str(self.description())
} }
} }
impl Error for HttpError { impl StdError for Error {
fn description(&self) -> &str { fn description(&self) -> &str {
match *self { match *self {
HttpMethodError => "Invalid Method specified", Method => "Invalid Method specified",
HttpUriError(_) => "Invalid Request URI specified", Uri(_) => "Invalid Request URI specified",
HttpVersionError => "Invalid HTTP version specified", Version => "Invalid HTTP version specified",
HttpHeaderError => "Invalid Header provided", Header => "Invalid Header provided",
HttpTooLargeError => "Message head is too large", TooLarge => "Message head is too large",
HttpStatusError => "Invalid Status provided", Status => "Invalid Status provided",
HttpIoError(_) => "An IoError occurred while connecting to the specified network", Io(_) => "An IoError occurred while connecting to the specified network",
} }
} }
fn cause(&self) -> Option<&Error> { fn cause(&self) -> Option<&StdError> {
match *self { match *self {
HttpIoError(ref error) => Some(error), Io(ref error) => Some(error),
HttpUriError(ref error) => Some(error), Uri(ref error) => Some(error),
_ => None, _ => None,
} }
} }
} }
impl From<IoError> for HttpError { impl From<IoError> for Error {
fn from(err: IoError) -> HttpError { fn from(err: IoError) -> Error {
HttpIoError(err) Io(err)
} }
} }
impl From<url::ParseError> for HttpError { impl From<url::ParseError> for Error {
fn from(err: url::ParseError) -> HttpError { fn from(err: url::ParseError) -> Error {
HttpUriError(err) Uri(err)
} }
} }
impl From<httparse::Error> for HttpError { impl From<httparse::Error> for Error {
fn from(err: httparse::Error) -> HttpError { fn from(err: httparse::Error) -> Error {
match err { match err {
httparse::Error::HeaderName => HttpHeaderError, httparse::Error::HeaderName => Header,
httparse::Error::HeaderValue => HttpHeaderError, httparse::Error::HeaderValue => Header,
httparse::Error::NewLine => HttpHeaderError, httparse::Error::NewLine => Header,
httparse::Error::Status => HttpStatusError, httparse::Error::Status => Status,
httparse::Error::Token => HttpHeaderError, httparse::Error::Token => Header,
httparse::Error::TooManyHeaders => HttpTooLargeError, httparse::Error::TooManyHeaders => TooLarge,
httparse::Error::Version => HttpVersionError, httparse::Error::Version => Version,
} }
} }
} }

View File

@@ -17,7 +17,6 @@ use typeable::Typeable;
use unicase::UniCase; use unicase::UniCase;
use self::internals::Item; use self::internals::Item;
use error::HttpResult;
pub use self::shared::*; pub use self::shared::*;
pub use self::common::*; pub use self::common::*;
@@ -113,7 +112,7 @@ impl Headers {
} }
#[doc(hidden)] #[doc(hidden)]
pub fn from_raw<'a>(raw: &[httparse::Header<'a>]) -> HttpResult<Headers> { pub fn from_raw<'a>(raw: &[httparse::Header<'a>]) -> ::Result<Headers> {
let mut headers = Headers::new(); let mut headers = Headers::new();
for header in raw { for header in raw {
trace!("raw header: {:?}={:?}", header.name, &header.value[..]); trace!("raw header: {:?}={:?}", header.name, &header.value[..]);

View File

@@ -13,8 +13,7 @@ use method::Method;
use status::StatusCode; use status::StatusCode;
use uri::RequestUri; use uri::RequestUri;
use version::HttpVersion::{self, Http10, Http11}; use version::HttpVersion::{self, Http10, Http11};
use HttpError::{HttpIoError, HttpTooLargeError}; use {Error};
use {HttpError, HttpResult};
use self::HttpReader::{SizedReader, ChunkedReader, EofReader, EmptyReader}; use self::HttpReader::{SizedReader, ChunkedReader, EofReader, EmptyReader};
use self::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; use self::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
@@ -334,17 +333,17 @@ const MAX_HEADERS: usize = 100;
/// Parses a request into an Incoming message head. /// Parses a request into an Incoming message head.
#[inline] #[inline]
pub fn parse_request<R: Read>(buf: &mut BufReader<R>) -> HttpResult<Incoming<(Method, RequestUri)>> { pub fn parse_request<R: Read>(buf: &mut BufReader<R>) -> ::Result<Incoming<(Method, RequestUri)>> {
parse::<R, httparse::Request, (Method, RequestUri)>(buf) parse::<R, httparse::Request, (Method, RequestUri)>(buf)
} }
/// Parses a response into an Incoming message head. /// Parses a response into an Incoming message head.
#[inline] #[inline]
pub fn parse_response<R: Read>(buf: &mut BufReader<R>) -> HttpResult<Incoming<RawStatus>> { pub fn parse_response<R: Read>(buf: &mut BufReader<R>) -> ::Result<Incoming<RawStatus>> {
parse::<R, httparse::Response, RawStatus>(buf) parse::<R, httparse::Response, RawStatus>(buf)
} }
fn parse<R: Read, T: TryParse<Subject=I>, I>(rdr: &mut BufReader<R>) -> HttpResult<Incoming<I>> { fn parse<R: Read, T: TryParse<Subject=I>, I>(rdr: &mut BufReader<R>) -> ::Result<Incoming<I>> {
loop { loop {
match try!(try_parse::<R, T, I>(rdr)) { match try!(try_parse::<R, T, I>(rdr)) {
httparse::Status::Complete((inc, len)) => { httparse::Status::Complete((inc, len)) => {
@@ -355,12 +354,12 @@ fn parse<R: Read, T: TryParse<Subject=I>, I>(rdr: &mut BufReader<R>) -> HttpResu
} }
match try!(rdr.read_into_buf()) { match try!(rdr.read_into_buf()) {
0 if rdr.get_buf().is_empty() => { 0 if rdr.get_buf().is_empty() => {
return Err(HttpIoError(io::Error::new( return Err(Error::Io(io::Error::new(
io::ErrorKind::ConnectionAborted, io::ErrorKind::ConnectionAborted,
"Connection closed" "Connection closed"
))) )))
}, },
0 => return Err(HttpTooLargeError), 0 => return Err(Error::TooLarge),
_ => () _ => ()
} }
} }
@@ -377,7 +376,7 @@ trait TryParse {
fn try_parse<'a>(headers: &'a mut [httparse::Header<'a>], buf: &'a [u8]) -> TryParseResult<Self::Subject>; fn try_parse<'a>(headers: &'a mut [httparse::Header<'a>], buf: &'a [u8]) -> TryParseResult<Self::Subject>;
} }
type TryParseResult<T> = Result<httparse::Status<(Incoming<T>, usize)>, HttpError>; type TryParseResult<T> = Result<httparse::Status<(Incoming<T>, usize)>, Error>;
impl<'a> TryParse for httparse::Request<'a, 'a> { impl<'a> TryParse for httparse::Request<'a, 'a> {
type Subject = (Method, RequestUri); type Subject = (Method, RequestUri);
@@ -552,12 +551,12 @@ mod tests {
#[test] #[test]
fn test_parse_tcp_closed() { fn test_parse_tcp_closed() {
use std::io::ErrorKind; use std::io::ErrorKind;
use error::HttpError::HttpIoError; use error::Error;
let mut empty = MockStream::new(); let mut empty = MockStream::new();
let mut buf = BufReader::new(&mut empty); let mut buf = BufReader::new(&mut empty);
match parse_request(&mut buf) { match parse_request(&mut buf) {
Err(HttpIoError(ref e)) if e.kind() == ErrorKind::ConnectionAborted => (), Err(Error::Io(ref e)) if e.kind() == ErrorKind::ConnectionAborted => (),
other => panic!("unexpected result: {:?}", other) other => panic!("unexpected result: {:?}", other)
} }
} }

View File

@@ -149,7 +149,7 @@ extern crate test;
pub use mimewrapper::mime; pub use mimewrapper::mime;
pub use url::Url; pub use url::Url;
pub use client::Client; pub use client::Client;
pub use error::{HttpResult, HttpError}; pub use error::{Result, Error};
pub use method::Method::{Get, Head, Post, Delete}; pub use method::Method::{Get, Head, Post, Delete};
pub use status::StatusCode::{Ok, BadRequest, NotFound}; pub use status::StatusCode::{Ok, BadRequest, NotFound};
pub use server::Server; pub use server::Server;

View File

@@ -3,7 +3,7 @@ use std::fmt;
use std::str::FromStr; use std::str::FromStr;
use std::convert::AsRef; use std::convert::AsRef;
use error::HttpError; use error::Error;
use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch, use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch,
Extension}; Extension};
@@ -87,10 +87,10 @@ impl Method {
} }
impl FromStr for Method { impl FromStr for Method {
type Err = HttpError; type Err = Error;
fn from_str(s: &str) -> Result<Method, HttpError> { fn from_str(s: &str) -> Result<Method, Error> {
if s == "" { if s == "" {
Err(HttpError::HttpMethodError) Err(Error::Method)
} else { } else {
Ok(match s { Ok(match s {
"OPTIONS" => Options, "OPTIONS" => Options,

View File

@@ -33,8 +33,7 @@ pub use self::response::Response;
pub use net::{Fresh, Streaming}; pub use net::{Fresh, Streaming};
use HttpError::HttpIoError; use Error;
use {HttpResult};
use buffer::BufReader; use buffer::BufReader;
use header::{Headers, Expect}; use header::{Headers, Expect};
use http; use http;
@@ -113,7 +112,7 @@ impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> {
impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> { impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> {
/// Binds to a socket, and starts handling connections using a task pool. /// Binds to a socket, and starts handling connections using a task pool.
pub fn listen_threads<T: ToSocketAddrs>(self, addr: T, threads: usize) -> HttpResult<Listening> { pub fn listen_threads<T: ToSocketAddrs>(self, addr: T, threads: usize) -> ::Result<Listening> {
let listener = try!(match self.ssl { let listener = try!(match self.ssl {
Some(SslConfig::CertAndKey(cert, key)) => HttpListener::https(addr, cert, key), Some(SslConfig::CertAndKey(cert, key)) => HttpListener::https(addr, cert, key),
Some(SslConfig::Context(ssl_context)) => HttpListener::https_with_context(addr, ssl_context), Some(SslConfig::Context(ssl_context)) => HttpListener::https_with_context(addr, ssl_context),
@@ -123,7 +122,7 @@ impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> {
} }
/// Binds to a socket and starts handling connections. /// Binds to a socket and starts handling connections.
pub fn listen<T: ToSocketAddrs>(self, addr: T) -> HttpResult<Listening> { pub fn listen<T: ToSocketAddrs>(self, addr: T) -> ::Result<Listening> {
self.listen_threads(addr, num_cpus::get() * 5 / 4) self.listen_threads(addr, num_cpus::get() * 5 / 4)
} }
} }
@@ -133,12 +132,12 @@ H: Handler + 'static,
L: NetworkListener<Stream=S> + Send + 'static, L: NetworkListener<Stream=S> + Send + 'static,
S: NetworkStream + Clone + Send> Server<'a, H, L> { S: NetworkStream + Clone + Send> Server<'a, H, L> {
/// Creates a new server that will handle `HttpStream`s. /// Creates a new server that will handle `HttpStream`s.
pub fn with_listener(self, listener: L, threads: usize) -> HttpResult<Listening> { pub fn with_listener(self, listener: L, threads: usize) -> ::Result<Listening> {
with_listener(self.handler, listener, threads) with_listener(self.handler, listener, threads)
} }
} }
fn with_listener<H, L>(handler: H, mut listener: L, threads: usize) -> HttpResult<Listening> fn with_listener<H, L>(handler: H, mut listener: L, threads: usize) -> ::Result<Listening>
where H: Handler + 'static, where H: Handler + 'static,
L: NetworkListener + Send + 'static { L: NetworkListener + Send + 'static {
let socket = try!(listener.local_addr()); let socket = try!(listener.local_addr());
@@ -175,11 +174,11 @@ where S: NetworkStream + Clone, H: Handler {
while keep_alive { while keep_alive {
let req = match Request::new(&mut rdr, addr) { let req = match Request::new(&mut rdr, addr) {
Ok(req) => req, Ok(req) => req,
Err(HttpIoError(ref e)) if e.kind() == ErrorKind::ConnectionAborted => { Err(Error::Io(ref e)) if e.kind() == ErrorKind::ConnectionAborted => {
trace!("tcp closed, cancelling keep-alive loop"); trace!("tcp closed, cancelling keep-alive loop");
break; break;
} }
Err(HttpIoError(e)) => { Err(Error::Io(e)) => {
debug!("ioerror in keepalive loop = {:?}", e); debug!("ioerror in keepalive loop = {:?}", e);
break; break;
} }
@@ -235,7 +234,7 @@ impl Drop for Listening {
impl Listening { impl Listening {
/// Stop the server from listening to its socket address. /// Stop the server from listening to its socket address.
pub fn close(&mut self) -> HttpResult<()> { pub fn close(&mut self) -> ::Result<()> {
let _ = self._guard.take(); let _ = self._guard.take();
debug!("closing server"); debug!("closing server");
//try!(self.acceptor.close()); //try!(self.acceptor.close());

View File

@@ -5,7 +5,6 @@
use std::io::{self, Read}; use std::io::{self, Read};
use std::net::SocketAddr; use std::net::SocketAddr;
use {HttpResult};
use buffer::BufReader; use buffer::BufReader;
use net::NetworkStream; use net::NetworkStream;
use version::{HttpVersion}; use version::{HttpVersion};
@@ -35,7 +34,7 @@ impl<'a, 'b: 'a> Request<'a, 'b> {
/// Create a new Request, reading the StartLine and Headers so they are /// Create a new Request, reading the StartLine and Headers so they are
/// immediately useful. /// immediately useful.
pub fn new(mut stream: &'a mut BufReader<&'b mut NetworkStream>, addr: SocketAddr) pub fn new(mut stream: &'a mut BufReader<&'b mut NetworkStream>, addr: SocketAddr)
-> HttpResult<Request<'a, 'b>> { -> ::Result<Request<'a, 'b>> {
let Incoming { version, subject: (method, uri), headers } = try!(http::parse_request(stream)); let Incoming { version, subject: (method, uri), headers } = try!(http::parse_request(stream));
debug!("Request Line: {:?} {:?} {:?}", method, uri, version); debug!("Request Line: {:?} {:?} {:?}", method, uri, version);

View File

@@ -3,7 +3,7 @@ use std::str::FromStr;
use url::Url; use url::Url;
use url::ParseError as UrlError; use url::ParseError as UrlError;
use error::HttpError; use Error;
/// The Request-URI of a Request's StartLine. /// The Request-URI of a Request's StartLine.
/// ///
@@ -50,12 +50,12 @@ pub enum RequestUri {
} }
impl FromStr for RequestUri { impl FromStr for RequestUri {
type Err = HttpError; type Err = Error;
fn from_str(s: &str) -> Result<RequestUri, HttpError> { fn from_str(s: &str) -> Result<RequestUri, Error> {
let bytes = s.as_bytes(); let bytes = s.as_bytes();
if bytes == [] { if bytes == [] {
Err(HttpError::HttpUriError(UrlError::InvalidCharacter)) Err(Error::Uri(UrlError::InvalidCharacter))
} else if bytes == b"*" { } else if bytes == b"*" {
Ok(RequestUri::Star) Ok(RequestUri::Star)
} else if bytes.starts_with(b"/") { } else if bytes.starts_with(b"/") {