use std::error::Error;
use std::fmt;
use std::io;
use std::io::Read;
use hyper;
use hyper::client::response;
use serde_json;
#[derive(Debug)]
pub enum EsError {
EsError(String),
EsServerError(String),
HttpError(hyper::error::Error),
IoError(io::Error),
JsonError(serde_json::error::Error)
}
impl From<io::Error> for EsError {
fn from(err: io::Error) -> EsError {
EsError::IoError(err)
}
}
impl From<hyper::error::Error> for EsError {
fn from(err: hyper::error::Error) -> EsError {
EsError::HttpError(err)
}
}
impl From<serde_json::error::Error> for EsError {
fn from(err: serde_json::error::Error) -> EsError {
EsError::JsonError(err)
}
}
impl<'a> From<&'a mut response::Response> for EsError {
fn from(err: &'a mut response::Response) -> EsError {
let mut body = String::new();
match err.read_to_string(&mut body) {
Ok(_) => (),
Err(_) => {
return EsError::EsServerError(format!("{} - cannot read response - {:?}",
err.status,
err));
}
}
EsError::EsServerError(format!("{} - {}",
err.status,
body))
}
}
impl Error for EsError {
fn description(&self) -> &str {
match *self {
EsError::EsError(ref err) => err,
EsError::EsServerError(ref err) => err,
EsError::HttpError(ref err) => err.description(),
EsError::IoError(ref err) => err.description(),
EsError::JsonError(ref err) => err.description()
}
}
fn cause(&self) -> Option<&Error> {
match *self {
EsError::EsError(_) => None,
EsError::EsServerError(_) => None,
EsError::HttpError(ref err) => Some(err as &Error),
EsError::IoError(ref err) => Some(err as &Error),
EsError::JsonError(ref err) => Some(err as &Error)
}
}
}
impl fmt::Display for EsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
EsError::EsError(ref s) => fmt::Display::fmt(s, f),
EsError::EsServerError(ref s) => fmt::Display::fmt(s, f),
EsError::HttpError(ref err) => fmt::Display::fmt(err, f),
EsError::IoError(ref err) => fmt::Display::fmt(err, f),
EsError::JsonError(ref err) => fmt::Display::fmt(err, f)
}
}
}