delopay 0.3.0

Official Rust SDK for the DeloPay payments API
Documentation
//! Error types returned by the SDK.

#[cfg(feature = "client")]
use serde::Deserialize;
use serde_json::Value;

/// Convenient result alias used throughout the crate.
pub type Result<T> = std::result::Result<T, DelopayError>;

/// Structured detail of an API error. Boxed inside [`DelopayError`] so the
/// success path of every `Result` stays small.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ApiError {
    /// HTTP status code.
    pub status: u16,
    /// Machine-readable error code (e.g. `HE_00`, `IR_01`, `AUTH_01`).
    pub code: String,
    /// Error category (e.g. `invalid_request`, `rate_limit_error`).
    pub error_type: String,
    /// Human-readable message.
    pub message: String,
    /// `x-request-id` response header, when present — include it in support requests.
    pub request_id: Option<String>,
    /// Structured, per-code context the API attaches under `error.data`
    /// (e.g. `{ "retry_after_secs": 248 }` on a lockout).
    pub data: Option<Value>,
}

/// Everything that can go wrong talking to DeloPay.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DelopayError {
    /// The API returned a non-2xx response with a structured error envelope.
    #[error("DeloPay API error {} [{}]: {}", .0.status, .0.code, .0.message)]
    Api(Box<ApiError>),

    /// The API key is missing, invalid, or revoked (HTTP 401).
    #[error("DeloPay authentication failed [{}]: {}", .0.code, .0.message)]
    Authentication(Box<ApiError>),

    /// The request timed out.
    #[error("DeloPay request timed out")]
    Timeout,

    /// A transport / network error occurred.
    ///
    /// Backend-independent. Downcast to the concrete backend error when you
    /// need its specifics, e.g.
    /// `e.downcast_ref::<hyper_util::client::legacy::Error>()`.
    #[error("DeloPay transport error: {0}")]
    Transport(Box<dyn std::error::Error + Send + Sync>),

    /// A JSON (de)serialization failure: either a response body could not be
    /// decoded into the expected type, or a request body could not be
    /// encoded. The latter direction is effectively unreachable in practice
    /// (request types are constructed from valid Rust values), but the
    /// fallible `serde_json` call still needs somewhere to route its error.
    #[error("failed to decode DeloPay response: {0}")]
    Decode(String),

    /// A webhook signature did not match the body.
    #[error("invalid webhook signature")]
    InvalidSignature,

    /// The `X-Webhook-Signature-512` header was malformed (not valid hex).
    #[error("invalid webhook signature format")]
    InvalidSignatureFormat,

    /// The client was configured incorrectly.
    #[error("invalid DeloPay configuration: {0}")]
    Config(String),

    /// A request was built with fields that cannot be serialized unambiguously.
    #[error("invalid DeloPay request: {0}")]
    InvalidRequest(String),
}

/// Wire shape of the API error envelope: `{ "error": { ... } }`.
///
/// Only the client parses HTTP responses, so this and `from_response` below
/// are gated with it. The `DelopayError` enum itself stays ungated — none of
/// its variants name a transport type.
#[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 {
    /// Build a typed error from a non-2xx response.
    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,
            }))
        }
    }
}