use std::time::Duration;
use thiserror::Error;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ErrorKind {
#[error("authentication failed: {0}")]
Authentication(String),
#[error("bad request: {0}")]
BadRequest(String),
#[error("not found: {0}")]
NotFound(String),
#[error("unprocessable entity: {0}")]
UnprocessableEntity(String),
#[error("rate limit exceeded: {0}")]
RateLimit(String),
#[error("internal server error: {0}")]
InternalServer(String),
#[error("service overloaded: {0}")]
Overloaded(String),
#[error("API error (status {status}): {message}")]
Api {
status: u16,
message: String,
},
#[error("connection error: {0}")]
Connection(String),
#[error("request timed out (configured timeout: {0:?})")]
Timeout(Duration),
#[error("response validation error: {message}{}", field_path.as_ref().map(|p| format!(" (field: {p})")).unwrap_or_default())]
ResponseValidation {
message: String,
field_path: Option<String>,
},
#[error("{0}")]
Validation(String),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("transport error: {0}")]
Transport(#[from] reqwest::Error),
}
impl ErrorKind {
pub fn is_retryable(&self) -> bool {
matches!(
self,
ErrorKind::RateLimit(_)
| ErrorKind::Overloaded(_)
| ErrorKind::InternalServer(_)
| ErrorKind::Connection(_)
| ErrorKind::Timeout(_)
)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct TypeSafeError {
kind: ErrorKind,
request_id: Option<String>,
}
impl TypeSafeError {
pub fn new(kind: ErrorKind) -> Self {
Self {
kind,
request_id: None,
}
}
pub fn with_request_id(kind: ErrorKind, request_id: Option<String>) -> Self {
Self { kind, request_id }
}
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
pub fn request_id(&self) -> Option<&str> {
self.request_id.as_deref()
}
pub fn is_retryable(&self) -> bool {
self.kind.is_retryable()
}
}
impl std::fmt::Display for TypeSafeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.kind)?;
if let Some(ref id) = self.request_id {
write!(f, " (request id: {id})")?;
}
Ok(())
}
}
impl std::error::Error for TypeSafeError {}
impl From<serde_json::Error> for TypeSafeError {
fn from(e: serde_json::Error) -> Self {
Self::new(ErrorKind::Json(e))
}
}
impl From<reqwest::Error> for TypeSafeError {
fn from(e: reqwest::Error) -> Self {
Self::new(ErrorKind::Transport(e))
}
}
impl From<ErrorKind> for TypeSafeError {
fn from(kind: ErrorKind) -> Self {
Self::new(kind)
}
}
pub type Result<T> = std::result::Result<T, TypeSafeError>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn response_validation_with_field_path() {
let err = TypeSafeError::new(ErrorKind::ResponseValidation {
message: "expected a number".to_string(),
field_path: Some("answers.billing.noul".to_string()),
});
let display = format!("{err}");
assert!(display.contains("expected a number"));
assert!(display.contains("answers.billing.noul"));
}
#[test]
fn response_validation_without_field_path() {
let err = TypeSafeError::new(ErrorKind::ResponseValidation {
message: "malformed JSON".to_string(),
field_path: None,
});
let display = format!("{err}");
assert!(display.contains("malformed JSON"));
assert!(!display.contains("field:"));
}
#[test]
fn response_validation_is_not_retryable() {
let kind = ErrorKind::ResponseValidation {
message: "bad".to_string(),
field_path: None,
};
assert!(!kind.is_retryable());
}
#[test]
fn request_id_displayed_when_present() {
let err = TypeSafeError::with_request_id(
ErrorKind::Authentication("bad key".to_string()),
Some("req-123".to_string()),
);
let display = format!("{err}");
assert!(display.contains("bad key"));
assert!(display.contains("req-123"));
}
#[test]
fn request_id_absent_when_not_provided() {
let err = TypeSafeError::new(ErrorKind::Authentication("bad key".to_string()));
let display = format!("{err}");
assert!(display.contains("bad key"));
assert!(!display.contains("request id"));
}
#[test]
fn from_error_kind_creates_error() {
let kind = ErrorKind::Validation("test".to_string());
let err: TypeSafeError = kind.into();
assert!(matches!(err.kind(), ErrorKind::Validation(_)));
}
}