use serde::Deserialize;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error(
"missing Bytebury API token: set `{env_var}` in your environment or `.env` file (create a key at https://bytebury.com/api-keys)"
)]
MissingApiToken {
env_var: String,
},
#[error("invalid client configuration: {0}")]
InvalidConfig(String),
#[error("Bytebury API error ({status}): {message}")]
Api {
status: u16,
message: String,
},
#[error("HTTP request failed: {0}")]
Http(#[from] reqwest::Error),
#[error("JSON serialization error: {0}")]
Json(#[from] serde_json::Error),
#[error("base64 decode error: {0}")]
Base64(#[from] base64::DecodeError),
#[error("webhook signature verification failed: {0}")]
WebhookSignature(String),
}
impl Error {
pub fn status(&self) -> Option<u16> {
match self {
Self::Api { status, .. } => Some(*status),
Self::Http(err) => err.status().map(|s| s.as_u16()),
_ => None,
}
}
pub fn is_bad_request(&self) -> bool {
self.status() == Some(400)
}
pub fn is_unauthorized(&self) -> bool {
self.status() == Some(401)
}
pub fn is_forbidden(&self) -> bool {
self.status() == Some(403)
}
pub fn is_not_found(&self) -> bool {
self.status() == Some(404)
}
pub fn is_conflict(&self) -> bool {
self.status() == Some(409)
}
pub fn is_payload_too_large(&self) -> bool {
self.status() == Some(413)
}
pub fn is_rate_limited(&self) -> bool {
self.status() == Some(429)
}
}
#[derive(Deserialize)]
pub(crate) struct ApiErrorBody {
pub(crate) error: String,
}
pub(crate) fn parse_api_error(status: u16, body: &[u8]) -> Error {
if let Ok(parsed) = serde_json::from_slice::<ApiErrorBody>(body) {
return Error::Api {
status,
message: parsed.error,
};
}
let fallback = String::from_utf8_lossy(body).trim().to_string();
let message = if fallback.is_empty() {
format!("HTTP {status}")
} else {
fallback
};
Error::Api { status, message }
}