use reqwest::StatusCode;
use serde::Deserialize;
use thiserror::Error;
pub type Result<T> = std::result::Result<T, UspsError>;
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ApiErrorDetail {
#[serde(default)]
pub code: Option<String>,
#[serde(default)]
pub message: Option<String>,
#[serde(default)]
pub source: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct UspsApiErrorResponse {
#[serde(default)]
pub error: Option<String>,
#[serde(default)]
pub error_description: Option<String>,
#[serde(default)]
pub errors: Vec<ApiErrorDetail>,
#[serde(default)]
pub message: Option<String>,
}
#[derive(Debug, Error)]
pub enum UspsError {
#[error("Error de transporte HTTP: {0}")]
Http(#[from] reqwest::Error),
#[error("Error de serialización/deserialización JSON: {0}")]
Serialization(#[from] serde_json::Error),
#[error("Fallo de autenticación OAuth 2.0: {0}")]
Auth(String),
#[error("Error de API USPS (HTTP {status}): {message}")]
Api {
status: StatusCode,
message: String,
response: Option<UspsApiErrorResponse>,
},
#[error("Parámetro de entrada inválido: {0}")]
InvalidInput(String),
#[error("Recurso no encontrado: {0}")]
NotFound(String),
#[error("Error interno del SDK: {0}")]
Internal(String),
}
impl UspsError {
#[must_use]
pub fn from_response(status: StatusCode, body: &str) -> Self {
if let Ok(parsed) = serde_json::from_str::<UspsApiErrorResponse>(body) {
let message = parsed
.error_description
.clone()
.or_else(|| parsed.message.clone())
.or_else(|| parsed.error.clone())
.unwrap_or_else(|| format!("HTTP status {status}"));
Self::Api {
status,
message,
response: Some(parsed),
}
} else {
Self::Api {
status,
message: if body.is_empty() {
format!("HTTP status {status}")
} else {
body.to_string()
},
response: None,
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_response_should_parse_structured_json() {
let raw = r#"{
"error": "invalid_client",
"error_description": "Invalid client credentials provided"
}"#;
let err = UspsError::from_response(StatusCode::UNAUTHORIZED, raw);
match err {
UspsError::Api {
status,
message,
response,
} => {
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(message, "Invalid client credentials provided");
assert!(response.is_some());
}
_ => panic!("Expected UspsError::Api variant"),
}
}
#[test]
fn from_response_should_fallback_when_body_is_not_json() {
let raw = "Bad Gateway";
let err = UspsError::from_response(StatusCode::BAD_GATEWAY, raw);
match err {
UspsError::Api {
status,
message,
response,
} => {
assert_eq!(status, StatusCode::BAD_GATEWAY);
assert_eq!(message, "Bad Gateway");
assert!(response.is_none());
}
_ => panic!("Expected UspsError::Api variant"),
}
}
}