use serde_json::Value;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("API error (status {status}): {message}")]
Api {
status: u16,
code: Option<String>,
message: String,
body: Option<Value>,
},
#[error("authentication error (status {status}): {message}")]
Auth {
status: u16,
code: Option<String>,
message: String,
body: Option<Value>,
},
#[error("permission denied (status {status}): {message}")]
PermissionDenied {
status: u16,
code: Option<String>,
message: String,
body: Option<Value>,
},
#[error("not found (status {status}): {message}")]
NotFound {
status: u16,
code: Option<String>,
message: String,
body: Option<Value>,
},
#[error("validation error (status {status}): {message}")]
Validation {
status: u16,
code: Option<String>,
message: String,
body: Option<Value>,
},
#[error("rate limited: {message}")]
RateLimit {
retry_after: Option<f64>,
code: Option<String>,
message: String,
body: Option<Value>,
},
#[error("server error (status {status}): {message}")]
Server {
status: u16,
code: Option<String>,
message: String,
body: Option<Value>,
},
#[error("connection error: {0}")]
Connection(#[from] reqwest::Error),
#[error("webhook verification failed: {0}")]
WebhookVerification(String),
}
impl Error {
pub fn status(&self) -> Option<u16> {
match self {
Error::Api { status, .. }
| Error::Auth { status, .. }
| Error::PermissionDenied { status, .. }
| Error::NotFound { status, .. }
| Error::Validation { status, .. }
| Error::Server { status, .. } => Some(*status),
Error::RateLimit { .. } => Some(429),
_ => None,
}
}
pub fn code(&self) -> Option<&str> {
match self {
Error::Api { code, .. }
| Error::Auth { code, .. }
| Error::PermissionDenied { code, .. }
| Error::NotFound { code, .. }
| Error::Validation { code, .. }
| Error::RateLimit { code, .. }
| Error::Server { code, .. } => code.as_deref(),
_ => None,
}
}
pub fn retry_after(&self) -> Option<f64> {
match self {
Error::RateLimit { retry_after, .. } => *retry_after,
_ => None,
}
}
pub(crate) fn from_status(
status: u16,
code: Option<String>,
message: String,
body: Option<Value>,
retry_after: Option<f64>,
) -> Error {
match status {
400 | 422 => Error::Validation { status, code, message, body },
401 => Error::Auth { status, code, message, body },
403 => Error::PermissionDenied { status, code, message, body },
404 => Error::NotFound { status, code, message, body },
429 => Error::RateLimit { retry_after, code, message, body },
s if s >= 500 => Error::Server { status, code, message, body },
_ => Error::Api { status, code, message, body },
}
}
pub(crate) fn from_response(status: u16, body_text: &str, retry_after: Option<f64>) -> Error {
let mut code: Option<String> = None;
let mut message = format!("Request failed with status {status}.");
let parsed: Option<Value> = serde_json::from_str(body_text).ok();
if let Some(parsed_body) = &parsed {
match parsed_body.get("error") {
Some(Value::Object(err)) => {
if let Some(Value::String(c)) = err.get("code") {
code = Some(c.clone());
}
if let Some(Value::String(m)) = err.get("message") {
message = m.clone();
}
}
Some(Value::String(m)) => message = m.clone(),
_ => {}
}
}
Error::from_status(status, code, message, parsed, retry_after)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make(status: u16) -> Error {
Error::from_status(status, Some("some_code".into()), "msg".into(), None, Some(7.0))
}
#[test]
fn maps_statuses_to_variants() {
assert!(matches!(make(400), Error::Validation { status: 400, .. }));
assert!(matches!(make(422), Error::Validation { status: 422, .. }));
assert!(matches!(make(401), Error::Auth { status: 401, .. }));
assert!(matches!(make(403), Error::PermissionDenied { status: 403, .. }));
assert!(matches!(make(404), Error::NotFound { status: 404, .. }));
assert!(matches!(make(429), Error::RateLimit { retry_after: Some(r), .. } if r == 7.0));
assert!(matches!(make(500), Error::Server { status: 500, .. }));
assert!(matches!(make(503), Error::Server { status: 503, .. }));
assert!(matches!(make(418), Error::Api { status: 418, .. }));
}
#[test]
fn accessors_expose_status_code_retry_after() {
let err = make(429);
assert_eq!(err.status(), Some(429));
assert_eq!(err.code(), Some("some_code"));
assert_eq!(err.retry_after(), Some(7.0));
let err = make(404);
assert_eq!(err.status(), Some(404));
assert_eq!(err.retry_after(), None);
}
#[test]
fn parses_error_body_envelope() {
let err = Error::from_response(
422,
r#"{"error":{"code":"validation_error","message":"content is required"}}"#,
None,
);
assert!(matches!(&err, Error::Validation { status: 422, .. }));
assert_eq!(err.code(), Some("validation_error"));
assert_eq!(err.to_string(), "validation error (status 422): content is required");
}
#[test]
fn tolerates_non_json_error_body() {
let err = Error::from_response(413, "<html>Request Entity Too Large</html>", None);
assert!(matches!(&err, Error::Api { status: 413, body: None, .. }));
assert_eq!(err.to_string(), "API error (status 413): Request failed with status 413.");
}
}