#[cfg(feature = "client")]
use serde::Deserialize;
use serde_json::Value;
pub type Result<T> = std::result::Result<T, DelopayError>;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ApiError {
pub status: u16,
pub code: String,
pub error_type: String,
pub message: String,
pub request_id: Option<String>,
pub data: Option<Value>,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DelopayError {
#[error("DeloPay API error {} [{}]: {}", .0.status, .0.code, .0.message)]
Api(Box<ApiError>),
#[error("DeloPay authentication failed [{}]: {}", .0.code, .0.message)]
Authentication(Box<ApiError>),
#[error("DeloPay request timed out")]
Timeout,
#[error("DeloPay transport error: {0}")]
Transport(Box<dyn std::error::Error + Send + Sync>),
#[error("failed to decode DeloPay response: {0}")]
Decode(String),
#[error("invalid webhook signature")]
InvalidSignature,
#[error("invalid webhook signature format")]
InvalidSignatureFormat,
#[error("invalid DeloPay configuration: {0}")]
Config(String),
#[error("invalid DeloPay request: {0}")]
InvalidRequest(String),
}
#[cfg(feature = "client")]
#[derive(Debug, Deserialize)]
struct ErrorEnvelope {
error: ApiErrorBody,
}
#[cfg(feature = "client")]
#[derive(Debug, Deserialize)]
struct ApiErrorBody {
#[serde(default)]
r#type: Option<String>,
#[serde(default)]
code: Option<String>,
#[serde(default)]
message: Option<String>,
#[serde(default)]
data: Option<Value>,
}
#[cfg(feature = "client")]
impl DelopayError {
pub(crate) fn from_response(status: u16, request_id: Option<String>, body: &[u8]) -> Self {
let parsed: Option<ApiErrorBody> = serde_json::from_slice::<ErrorEnvelope>(body)
.map(|e| e.error)
.ok();
let code = parsed
.as_ref()
.and_then(|b| b.code.clone())
.unwrap_or_else(|| "unknown".to_string());
let error_type = parsed
.as_ref()
.and_then(|b| b.r#type.clone())
.unwrap_or_else(|| "api_error".to_string());
let message = parsed
.as_ref()
.and_then(|b| b.message.clone())
.unwrap_or_else(|| {
let raw = String::from_utf8_lossy(body);
if raw.trim().is_empty() {
format!("HTTP {status}")
} else {
raw.chars().take(500).collect()
}
});
let data = parsed.and_then(|b| b.data);
if status == 401 {
DelopayError::Authentication(Box::new(ApiError {
status,
code: if code == "unknown" {
"AUTH_01".to_string()
} else {
code
},
error_type: "authentication_error".to_string(),
message,
request_id,
data,
}))
} else {
DelopayError::Api(Box::new(ApiError {
status,
code,
error_type,
message,
request_id,
data,
}))
}
}
}