Merge pull request #463 from hyperium/error-rename

refactor(error): remove redundant parts of error names
This commit is contained in:
Sean McArthur
2015-05-05 12:34:00 -07:00
11 changed files with 81 additions and 87 deletions

View File

@@ -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<Response> {
pub fn send(self) -> ::Result<Response> {
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))

View File

@@ -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<W> Request<W> {
impl Request<Fresh> {
/// 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);
Request::with_connector(method, url, &mut conn)
}
/// Create a new client request with a specific underlying NetworkStream.
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>,
S: Into<Box<NetworkStream + Send>> {
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,
/// 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();
//TODO: this needs a test
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.
///
/// 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
if !http::should_keep_alive(self.version, &self.headers) {
try!(raw.close(Shutdown::Write));

View File

@@ -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<S = HttpStream> {
impl Response {
/// 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 head = try!(http::parse_response(&mut stream));

View File

@@ -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<T> = Result<T, HttpError>;
/// Result type often returned from methods that can have hyper `Error`s.
pub type Result<T> = ::std::result::Result<T, Error>;
/// 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<IoError> for HttpError {
fn from(err: IoError) -> HttpError {
HttpIoError(err)
impl From<IoError> for Error {
fn from(err: IoError) -> Error {
Io(err)
}
}
impl From<url::ParseError> for HttpError {
fn from(err: url::ParseError) -> HttpError {
HttpUriError(err)
impl From<url::ParseError> for Error {
fn from(err: url::ParseError) -> Error {
Uri(err)
}
}
impl From<httparse::Error> for HttpError {
fn from(err: httparse::Error) -> HttpError {
impl From<httparse::Error> 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,
}
}
}

View File

@@ -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<Headers> {
pub fn from_raw<'a>(raw: &[httparse::Header<'a>]) -> ::Result<Headers> {
let mut headers = Headers::new();
for header in raw {
trace!("raw header: {:?}={:?}", header.name, &header.value[..]);

View File

@@ -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<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)
}
/// Parses a response into an Incoming message head.
#[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)
}
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 {
match try!(try_parse::<R, T, I>(rdr)) {
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()) {
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<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> {
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)
}
}

View File

@@ -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;

View File

@@ -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<Method, HttpError> {
type Err = Error;
fn from_str(s: &str) -> Result<Method, Error> {
if s == "" {
Err(HttpError::HttpMethodError)
Err(Error::Method)
} else {
Ok(match s {
"OPTIONS" => Options,

View File

@@ -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<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 {
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<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)
}
}
@@ -133,12 +132,12 @@ H: Handler + 'static,
L: NetworkListener<Stream=S> + 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<Listening> {
pub fn with_listener(self, listener: L, threads: usize) -> ::Result<Listening> {
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,
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());

View File

@@ -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<Request<'a, 'b>> {
-> ::Result<Request<'a, 'b>> {
let Incoming { version, subject: (method, uri), headers } = try!(http::parse_request(stream));
debug!("Request Line: {:?} {:?} {:?}", method, uri, version);

View File

@@ -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<RequestUri, HttpError> {
fn from_str(s: &str) -> Result<RequestUri, Error> {
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"/") {