1use std::error::Error;
20use std::fmt;
21use std::io::{self, Read};
22
23use serde_json;
24
25#[derive(Debug)]
30pub enum EsError {
31 EsError(String),
33
34 EsServerError(String),
36
37 HttpError(reqwest::Error),
39
40 IoError(io::Error),
42
43 JsonError(serde_json::error::Error),
45}
46
47impl From<io::Error> for EsError {
48 fn from(err: io::Error) -> EsError {
49 EsError::IoError(err)
50 }
51}
52
53impl From<reqwest::Error> for EsError {
54 fn from(err: reqwest::Error) -> EsError {
55 EsError::HttpError(err)
56 }
57}
58
59impl From<serde_json::error::Error> for EsError {
60 fn from(err: serde_json::error::Error) -> EsError {
61 EsError::JsonError(err)
62 }
63}
64
65impl<'a> From<&'a mut reqwest::Response> for EsError {
66 fn from(err: &'a mut reqwest::Response) -> EsError {
67 let mut body = String::new();
68 match err.read_to_string(&mut body) {
69 Ok(_) => (),
70 Err(_) => {
71 return EsError::EsServerError(format!(
72 "{} - cannot read response - {:?}",
73 err.status(),
74 err
75 ));
76 }
77 }
78 EsError::EsServerError(format!("{} - {}", err.status(), body))
79 }
80}
81
82impl Error for EsError {
83 fn description(&self) -> &str {
84 match *self {
85 EsError::EsError(ref err) => err,
86 EsError::EsServerError(ref err) => err,
87 EsError::HttpError(ref err) => err.description(),
88 EsError::IoError(ref err) => err.description(),
89 EsError::JsonError(ref err) => err.description(),
90 }
91 }
92
93 fn cause(&self) -> Option<&dyn Error> {
94 match *self {
95 EsError::EsError(_) => None,
96 EsError::EsServerError(_) => None,
97 EsError::HttpError(ref err) => Some(err as &dyn Error),
98 EsError::IoError(ref err) => Some(err as &dyn Error),
99 EsError::JsonError(ref err) => Some(err as &dyn Error),
100 }
101 }
102}
103
104impl fmt::Display for EsError {
105 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
106 match *self {
107 EsError::EsError(ref s) => fmt::Display::fmt(s, f),
108 EsError::EsServerError(ref s) => fmt::Display::fmt(s, f),
109 EsError::HttpError(ref err) => fmt::Display::fmt(err, f),
110 EsError::IoError(ref err) => fmt::Display::fmt(err, f),
111 EsError::JsonError(ref err) => fmt::Display::fmt(err, f),
112 }
113 }
114}