use std::fmt;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Http(Box<dyn std::error::Error + Send + Sync>),
RequestBuild(String),
Parse(Box<dyn std::error::Error + Send + Sync>),
Utf8(std::string::FromUtf8Error),
Json(serde_json::Error),
}
impl Error {
pub fn parse<E: std::error::Error + Send + Sync + 'static>(err: E) -> Self {
Self::Parse(Box::new(err))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Http(e) => write!(f, "http error: {e}"),
Self::RequestBuild(msg) => write!(f, "failed to build request: {msg}"),
Self::Parse(e) => write!(f, "failed to parse response: {e}"),
Self::Utf8(e) => write!(f, "response body is not valid UTF-8: {e}"),
Self::Json(e) => write!(f, "response body is not valid JSON: {e}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Http(e) | Self::Parse(e) => Some(&**e),
Self::Utf8(e) => Some(e),
Self::Json(e) => Some(e),
Self::RequestBuild(_) => None,
}
}
}
impl From<std::string::FromUtf8Error> for Error {
fn from(err: std::string::FromUtf8Error) -> Self {
Self::Utf8(err)
}
}
impl From<serde_json::Error> for Error {
fn from(err: serde_json::Error) -> Self {
Self::Json(err)
}
}
#[cfg(feature = "reqwest")]
impl From<reqwest::Error> for Error {
fn from(err: reqwest::Error) -> Self {
Self::Http(Box::new(err))
}
}