use serde::Deserialize;
#[derive(Debug, Clone, Deserialize)]
pub struct Problem {
#[serde(default)]
pub r#type: String,
#[serde(default)]
pub title: String,
#[serde(default)]
pub status: u16,
#[serde(default)]
pub detail: String,
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{method} {path}: {detail}")]
Status {
method: &'static str,
path: String,
status: u16,
detail: String,
problem: Option<Box<Problem>>,
body: String,
},
#[error("transport: {0}")]
Transport(#[from] reqwest::Error),
#[error("decoding {path}: {source}")]
Decode {
path: String,
#[source]
source: serde_json::Error,
},
#[error("invalid base URL: {0}")]
BaseUrl(String),
#[error("{path}: {source}")]
Io {
path: String,
#[source]
source: std::io::Error,
},
#[error("{verb} {path}: no answer within {after:?}")]
Timeout {
verb: &'static str,
path: String,
after: std::time::Duration,
},
#[error("not authenticated")]
Unauthenticated,
}
impl Error {
pub(crate) fn status(method: &'static str, path: &str, status: u16, body: String) -> Self {
let problem = serde_json::from_str::<Problem>(&body)
.ok()
.filter(|p| !p.r#type.is_empty() && p.status != 0)
.map(Box::new);
let detail = problem
.as_ref()
.map(|p| p.detail.clone())
.filter(|d| !d.is_empty())
.or_else(|| {
serde_json::from_str::<serde_json::Value>(&body)
.ok()
.and_then(|v| {
v.get("detail")
.or_else(|| v.get("message"))
.and_then(|m| m.as_str().map(str::to_owned))
})
})
.filter(|d| !d.is_empty())
.unwrap_or_else(|| {
if body.trim().is_empty() {
format!("status {status}")
} else {
body.trim().to_owned()
}
});
Error::Status {
method,
path: path.to_owned(),
status,
detail,
problem,
body,
}
}
pub fn http_status(&self) -> Option<u16> {
match self {
Error::Status { status, .. } => Some(*status),
_ => None,
}
}
pub fn is_unauthenticated(&self) -> bool {
matches!(self, Error::Unauthenticated) || self.http_status() == Some(401)
}
pub fn is_forbidden(&self) -> bool {
self.http_status() == Some(403)
}
pub fn is_unreachable(&self) -> bool {
matches!(self, Error::Transport(_) | Error::Timeout { .. })
}
pub fn detail(&self) -> String {
match self {
Error::Status { detail, .. } => detail.clone(),
other => other.to_string(),
}
}
}
pub type Result<T> = std::result::Result<T, Error>;