use std::collections::HashMap;
use thiserror::Error;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ValidationErrors {
pub message: Option<String>,
pub errors: HashMap<String, Vec<String>>,
pub raw: serde_json::Value,
}
impl ValidationErrors {
pub fn errors(&self) -> &HashMap<String, Vec<String>> {
&self.errors
}
pub(crate) fn from_value(value: serde_json::Value) -> Self {
let message = value
.get("message")
.and_then(|m| m.as_str())
.map(|s| s.to_string());
let mut errors = HashMap::new();
if let Some(map) = value.get("errors").and_then(|e| e.as_object()) {
for (field, msgs) in map {
let list = match msgs {
serde_json::Value::Array(arr) => arr
.iter()
.map(|v| match v {
serde_json::Value::String(s) => s.clone(),
other => other.to_string(),
})
.collect(),
serde_json::Value::String(s) => vec![s.clone()],
other => vec![other.to_string()],
};
errors.insert(field.clone(), list);
}
}
ValidationErrors {
message,
errors,
raw: value,
}
}
}
#[derive(Debug, Error)]
pub enum Error {
#[error("validation failed{}", .0.message.as_deref().map(|m| format!(": {m}")).unwrap_or_default())]
Validation(ValidationErrors),
#[error("resource not found")]
NotFound,
#[error("failed action: {0}")]
FailedAction(String),
#[error("rate limit exceeded")]
RateLimitExceeded {
resets_at: Option<i64>,
},
#[error("API error (status {status}): {body}")]
Api {
status: u16,
body: String,
},
#[error("invalid argument: {0}")]
InvalidArgument(String),
#[error("{0}")]
Unsupported(String),
#[error(transparent)]
Http(#[from] reqwest::Error),
#[error(transparent)]
Json(#[from] serde_json::Error),
#[error(transparent)]
Io(#[from] std::io::Error),
}