From 9ba074d150a55a749161317405fe8b28253c5a9d Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Thu, 16 Apr 2015 10:52:34 -0700 Subject: [PATCH] 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`. --- src/client/mod.rs | 12 +++--- src/client/request.rs | 9 ++--- src/client/response.rs | 3 +- src/error.rs | 84 +++++++++++++++++++++--------------------- src/header/mod.rs | 3 +- src/http.rs | 19 +++++----- src/lib.rs | 2 +- src/method.rs | 8 ++-- src/server/mod.rs | 17 ++++----- src/server/request.rs | 3 +- src/uri.rs | 8 ++-- 11 files changed, 81 insertions(+), 87 deletions(-) diff --git a/src/client/mod.rs b/src/client/mod.rs index 5587edb2f0..2dc5c555af 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -43,8 +43,8 @@ use header::{ContentLength, Location}; use method::Method; use net::{NetworkConnector, NetworkStream, HttpConnector, ContextVerifier}; use status::StatusClass::Redirection; -use {Url, HttpResult}; -use HttpError::HttpUriError; +use {Url}; +use Error; pub use self::pool::Pool; pub use self::request::Request; @@ -203,7 +203,7 @@ impl<'a, U: IntoUrl> RequestBuilder<'a, U> { } /// Execute this request and receive a Response back. - pub fn send(self) -> HttpResult { + pub fn send(self) -> ::Result { let RequestBuilder { client, method, url, headers, body } = self; let mut url = try!(url.into_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() { Some(host) => host, - None => return Err(HttpUriError(UrlError::EmptyHost)) + None => return Err(Error::Uri(UrlError::EmptyHost)) }; trace!("host={:?}", host); let port = match url.port_or_default() { Some(port) => port, - None => return Err(HttpUriError(UrlError::InvalidPort)) + None => return Err(Error::Uri(UrlError::InvalidPort)) }; trace!("port={:?}", port); Ok((host, port)) diff --git a/src/client/request.rs b/src/client/request.rs index eb2e0ea336..6b9c83acf0 100644 --- a/src/client/request.rs +++ b/src/client/request.rs @@ -12,7 +12,6 @@ use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming}; use http::{self, HttpWriter, LINE_ENDING}; use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; use version; -use HttpResult; use client::{Response, get_host_and_port}; @@ -43,14 +42,14 @@ impl Request { impl Request { /// Create a new client request. - pub fn new(method: method::Method, url: Url) -> HttpResult> { + pub fn new(method: method::Method, url: Url) -> ::Result> { let mut conn = HttpConnector(None); Request::with_connector(method, url, &mut conn) } /// Create a new client request with a specific underlying NetworkStream. pub fn with_connector(method: method::Method, url: Url, connector: &mut C) - -> HttpResult> where + -> ::Result> where C: NetworkConnector, S: Into> { let (host, port) = try!(get_host_and_port(&url)); @@ -76,7 +75,7 @@ impl Request { /// Consume a Fresh Request, writing the headers and method, /// returning a Streaming Request. - pub fn start(mut self) -> HttpResult> { + pub fn start(mut self) -> ::Result> { let mut uri = self.url.serialize_path().unwrap(); //TODO: this needs a test if let Some(ref q) = self.url.query { @@ -154,7 +153,7 @@ impl Request { /// Completes writing the request, and returns a response to read from. /// /// Consumes the Request. - pub fn send(self) -> HttpResult { + pub fn send(self) -> ::Result { let mut raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes if !http::should_keep_alive(self.version, &self.headers) { try!(raw.close(Shutdown::Write)); diff --git a/src/client/response.rs b/src/client/response.rs index 74175140d4..77ded4f3bd 100644 --- a/src/client/response.rs +++ b/src/client/response.rs @@ -12,7 +12,6 @@ use http::{self, HttpReader, RawStatus}; use http::HttpReader::{SizedReader, ChunkedReader, EofReader}; use status; use version; -use HttpResult; /// A response for a client request to a remote server. #[derive(Debug)] @@ -32,7 +31,7 @@ pub struct Response { impl Response { /// Creates a new response from a server. - pub fn new(stream: Box) -> HttpResult { + pub fn new(stream: Box) -> ::Result { let mut stream = BufReader::new(stream); let head = try!(http::parse_response(&mut stream)); diff --git a/src/error.rs b/src/error.rs index f5d591f922..d5db410d90 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,88 +1,88 @@ -//! HttpError and HttpResult module. -use std::error::Error; +//! Error and Result module. +use std::error::Error as StdError; use std::fmt; use std::io::Error as IoError; use httparse; use url; -use self::HttpError::{HttpMethodError, HttpUriError, HttpVersionError, - HttpHeaderError, HttpStatusError, HttpIoError, - HttpTooLargeError}; +use self::Error::{Method, Uri, Version, + Header, Status, Io, + TooLarge}; -/// Result type often returned from methods that can have `HttpError`s. -pub type HttpResult = Result; +/// Result type often returned from methods that can have hyper `Error`s. +pub type Result = ::std::result::Result; /// A set of errors that can occur parsing HTTP streams. #[derive(Debug)] -pub enum HttpError { +pub enum Error { /// An invalid `Method`, such as `GE,T`. - HttpMethodError, + Method, /// An invalid `RequestUri`, such as `exam ple.domain`. - HttpUriError(url::ParseError), + Uri(url::ParseError), /// An invalid `HttpVersion`, such as `HTP/1.1` - HttpVersionError, + Version, /// An invalid `Header`. - HttpHeaderError, + Header, /// A message head is too large to be reasonable. - HttpTooLargeError, + TooLarge, /// An invalid `Status`, such as `1337 ELITE`. - HttpStatusError, + Status, /// 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 { f.write_str(self.description()) } } -impl Error for HttpError { +impl StdError for Error { fn description(&self) -> &str { match *self { - HttpMethodError => "Invalid Method specified", - HttpUriError(_) => "Invalid Request URI specified", - HttpVersionError => "Invalid HTTP version specified", - HttpHeaderError => "Invalid Header provided", - HttpTooLargeError => "Message head is too large", - HttpStatusError => "Invalid Status provided", - HttpIoError(_) => "An IoError occurred while connecting to the specified network", + Method => "Invalid Method specified", + Uri(_) => "Invalid Request URI specified", + Version => "Invalid HTTP version specified", + Header => "Invalid Header provided", + TooLarge => "Message head is too large", + Status => "Invalid Status provided", + Io(_) => "An IoError occurred while connecting to the specified network", } } - fn cause(&self) -> Option<&Error> { + fn cause(&self) -> Option<&StdError> { match *self { - HttpIoError(ref error) => Some(error), - HttpUriError(ref error) => Some(error), + Io(ref error) => Some(error), + Uri(ref error) => Some(error), _ => None, } } } -impl From for HttpError { - fn from(err: IoError) -> HttpError { - HttpIoError(err) +impl From for Error { + fn from(err: IoError) -> Error { + Io(err) } } -impl From for HttpError { - fn from(err: url::ParseError) -> HttpError { - HttpUriError(err) +impl From for Error { + fn from(err: url::ParseError) -> Error { + Uri(err) } } -impl From for HttpError { - fn from(err: httparse::Error) -> HttpError { +impl From for Error { + fn from(err: httparse::Error) -> Error { match err { - httparse::Error::HeaderName => HttpHeaderError, - httparse::Error::HeaderValue => HttpHeaderError, - httparse::Error::NewLine => HttpHeaderError, - httparse::Error::Status => HttpStatusError, - httparse::Error::Token => HttpHeaderError, - httparse::Error::TooManyHeaders => HttpTooLargeError, - httparse::Error::Version => HttpVersionError, + httparse::Error::HeaderName => Header, + httparse::Error::HeaderValue => Header, + httparse::Error::NewLine => Header, + httparse::Error::Status => Status, + httparse::Error::Token => Header, + httparse::Error::TooManyHeaders => TooLarge, + httparse::Error::Version => Version, } } } diff --git a/src/header/mod.rs b/src/header/mod.rs index 56be8892a0..719d7989da 100644 --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -17,7 +17,6 @@ use typeable::Typeable; use unicase::UniCase; use self::internals::Item; -use error::HttpResult; pub use self::shared::*; pub use self::common::*; @@ -113,7 +112,7 @@ impl Headers { } #[doc(hidden)] - pub fn from_raw<'a>(raw: &[httparse::Header<'a>]) -> HttpResult { + pub fn from_raw<'a>(raw: &[httparse::Header<'a>]) -> ::Result { let mut headers = Headers::new(); for header in raw { trace!("raw header: {:?}={:?}", header.name, &header.value[..]); diff --git a/src/http.rs b/src/http.rs index 97c58ddcdd..fe884b263f 100644 --- a/src/http.rs +++ b/src/http.rs @@ -13,8 +13,7 @@ use method::Method; use status::StatusCode; use uri::RequestUri; use version::HttpVersion::{self, Http10, Http11}; -use HttpError::{HttpIoError, HttpTooLargeError}; -use {HttpError, HttpResult}; +use {Error}; use self::HttpReader::{SizedReader, ChunkedReader, EofReader, EmptyReader}; use self::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; @@ -334,17 +333,17 @@ const MAX_HEADERS: usize = 100; /// Parses a request into an Incoming message head. #[inline] -pub fn parse_request(buf: &mut BufReader) -> HttpResult> { +pub fn parse_request(buf: &mut BufReader) -> ::Result> { parse::(buf) } /// Parses a response into an Incoming message head. #[inline] -pub fn parse_response(buf: &mut BufReader) -> HttpResult> { +pub fn parse_response(buf: &mut BufReader) -> ::Result> { parse::(buf) } -fn parse, I>(rdr: &mut BufReader) -> HttpResult> { +fn parse, I>(rdr: &mut BufReader) -> ::Result> { loop { match try!(try_parse::(rdr)) { httparse::Status::Complete((inc, len)) => { @@ -355,12 +354,12 @@ fn parse, I>(rdr: &mut BufReader) -> HttpResu } match try!(rdr.read_into_buf()) { 0 if rdr.get_buf().is_empty() => { - return Err(HttpIoError(io::Error::new( + return Err(Error::Io(io::Error::new( io::ErrorKind::ConnectionAborted, "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; } -type TryParseResult = Result, usize)>, HttpError>; +type TryParseResult = Result, usize)>, Error>; impl<'a> TryParse for httparse::Request<'a, 'a> { type Subject = (Method, RequestUri); @@ -552,12 +551,12 @@ mod tests { #[test] fn test_parse_tcp_closed() { use std::io::ErrorKind; - use error::HttpError::HttpIoError; + use error::Error; let mut empty = MockStream::new(); let mut buf = BufReader::new(&mut empty); 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) } } diff --git a/src/lib.rs b/src/lib.rs index 8b122d17bd..edcba65629 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -149,7 +149,7 @@ extern crate test; pub use mimewrapper::mime; pub use url::Url; pub use client::Client; -pub use error::{HttpResult, HttpError}; +pub use error::{Result, Error}; pub use method::Method::{Get, Head, Post, Delete}; pub use status::StatusCode::{Ok, BadRequest, NotFound}; pub use server::Server; diff --git a/src/method.rs b/src/method.rs index ab841c98cd..acf4dedfe8 100644 --- a/src/method.rs +++ b/src/method.rs @@ -3,7 +3,7 @@ use std::fmt; use std::str::FromStr; use std::convert::AsRef; -use error::HttpError; +use error::Error; use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch, Extension}; @@ -87,10 +87,10 @@ impl Method { } impl FromStr for Method { - type Err = HttpError; - fn from_str(s: &str) -> Result { + type Err = Error; + fn from_str(s: &str) -> Result { if s == "" { - Err(HttpError::HttpMethodError) + Err(Error::Method) } else { Ok(match s { "OPTIONS" => Options, diff --git a/src/server/mod.rs b/src/server/mod.rs index 25986a861f..ff2c8de1d2 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -33,8 +33,7 @@ pub use self::response::Response; pub use net::{Fresh, Streaming}; -use HttpError::HttpIoError; -use {HttpResult}; +use Error; use buffer::BufReader; use header::{Headers, Expect}; use http; @@ -113,7 +112,7 @@ 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. - pub fn listen_threads(self, addr: T, threads: usize) -> HttpResult { + pub fn listen_threads(self, addr: T, threads: usize) -> ::Result { let listener = try!(match self.ssl { Some(SslConfig::CertAndKey(cert, key)) => HttpListener::https(addr, cert, key), 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. - pub fn listen(self, addr: T) -> HttpResult { + pub fn listen(self, addr: T) -> ::Result { self.listen_threads(addr, num_cpus::get() * 5 / 4) } } @@ -133,12 +132,12 @@ H: Handler + 'static, L: NetworkListener + Send + 'static, S: NetworkStream + Clone + Send> Server<'a, H, L> { /// Creates a new server that will handle `HttpStream`s. - pub fn with_listener(self, listener: L, threads: usize) -> HttpResult { + pub fn with_listener(self, listener: L, threads: usize) -> ::Result { with_listener(self.handler, listener, threads) } } -fn with_listener(handler: H, mut listener: L, threads: usize) -> HttpResult +fn with_listener(handler: H, mut listener: L, threads: usize) -> ::Result where H: Handler + 'static, L: NetworkListener + Send + 'static { let socket = try!(listener.local_addr()); @@ -175,11 +174,11 @@ where S: NetworkStream + Clone, H: Handler { while keep_alive { let req = match Request::new(&mut rdr, addr) { 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"); break; } - Err(HttpIoError(e)) => { + Err(Error::Io(e)) => { debug!("ioerror in keepalive loop = {:?}", e); break; } @@ -235,7 +234,7 @@ impl Drop for Listening { impl Listening { /// 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(); debug!("closing server"); //try!(self.acceptor.close()); diff --git a/src/server/request.rs b/src/server/request.rs index c99069f9fa..bc4dd1d28a 100644 --- a/src/server/request.rs +++ b/src/server/request.rs @@ -5,7 +5,6 @@ use std::io::{self, Read}; use std::net::SocketAddr; -use {HttpResult}; use buffer::BufReader; use net::NetworkStream; 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 /// immediately useful. pub fn new(mut stream: &'a mut BufReader<&'b mut NetworkStream>, addr: SocketAddr) - -> HttpResult> { + -> ::Result> { let Incoming { version, subject: (method, uri), headers } = try!(http::parse_request(stream)); debug!("Request Line: {:?} {:?} {:?}", method, uri, version); diff --git a/src/uri.rs b/src/uri.rs index 03dbd748a2..32f6a10432 100644 --- a/src/uri.rs +++ b/src/uri.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use url::Url; use url::ParseError as UrlError; -use error::HttpError; +use Error; /// The Request-URI of a Request's StartLine. /// @@ -50,12 +50,12 @@ pub enum RequestUri { } impl FromStr for RequestUri { - type Err = HttpError; + type Err = Error; - fn from_str(s: &str) -> Result { + fn from_str(s: &str) -> Result { let bytes = s.as_bytes(); if bytes == [] { - Err(HttpError::HttpUriError(UrlError::InvalidCharacter)) + Err(Error::Uri(UrlError::InvalidCharacter)) } else if bytes == b"*" { Ok(RequestUri::Star) } else if bytes.starts_with(b"/") {