use hyper::body::Bytes;
use std::fmt::Display;
#[derive(Debug)]
pub enum RequestError {
Fetch(hyper::Error),
Parse(serde_json::Error),
Request(String),
Status(u16, String),
ParseError(String),
}
impl Display for RequestError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RequestError::Fetch(e) => write!(f, "Fetch error: {}", e),
RequestError::Parse(e) => write!(f, "Parse error: {}", e),
RequestError::Request(e) => write!(f, "Request error: {}", e),
RequestError::Status(status, body) => {
write!(f, "Status error: {} - {}", status, body)
}
RequestError::ParseError(e) => write!(f, "Parse error: {}", e),
}
}
}
impl From<hyper::Error> for RequestError {
fn from(e: hyper::Error) -> Self {
RequestError::Fetch(e)
}
}
impl From<serde_json::Error> for RequestError {
fn from(e: serde_json::Error) -> Self {
RequestError::Parse(e)
}
}
impl From<String> for RequestError {
fn from(e: String) -> Self {
RequestError::Request(e)
}
}
impl From<&str> for RequestError {
fn from(s: &str) -> Self {
RequestError::Request(s.to_string())
}
}
impl From<(u16, String)> for RequestError {
fn from((status, body): (u16, String)) -> Self {
RequestError::Status(status, body)
}
}
impl From<(u16, Bytes)> for RequestError {
fn from((status, body): (u16, Bytes)) -> Self {
RequestError::Status(
status,
match String::from_utf8(body.to_vec()) {
Ok(s) => s,
Err(_) => String::from("Error while parsing body"),
},
)
}
}
impl From<url::ParseError> for RequestError {
fn from(e: url::ParseError) -> Self {
RequestError::ParseError(e.to_string())
}
}
impl From<hyper::http::Error> for RequestError {
fn from(e: hyper::http::Error) -> Self {
RequestError::ParseError(e.to_string())
}
}