hatang 0.1.1

Official Rust client for the Ha Tang (Hạ Tầng) API: transactional email, live chat and support CRM, VietQR payments, AI chatbot knowledge and webhook verification. Async (Tokio) and blocking.
Documentation
use std::fmt;

/// Everything a call or a signature check can fail with.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The API answered with an error, or could not be reached.
    ///
    /// `status` is the HTTP status, or `0` when Ha Tang was not reached (network error, timeout).
    /// `name` is the API's error code (`validation_error`, `not_found`, `rate_limit_exceeded`…).
    #[error("{status} {name}: {message}")]
    Api {
        status: u16,
        name: String,
        message: String,
    },
    /// A webhook delivery or IPN call whose signature (or timestamp) does not match.
    #[error("{0}")]
    Signature(String),
    /// The client could not be set up (no API key, an invalid base URL…).
    #[error("{0}")]
    Config(String),
    /// A request body could not be encoded, or a response did not have the expected shape.
    #[error("JSON: {0}")]
    Json(#[from] serde_json::Error),
}

impl Error {
    /// The HTTP status of an API error (`0` when Ha Tang was not reached); `None` for other errors.
    pub fn status(&self) -> Option<u16> {
        match self {
            Error::Api { status, .. } => Some(*status),
            _ => None,
        }
    }

    /// The API's error code (`validation_error`, `not_found`…); `None` for other errors.
    pub fn name(&self) -> Option<&str> {
        match self {
            Error::Api { name, .. } => Some(name),
            _ => None,
        }
    }

    /// True for outages worth retrying: unreachable, rate limited, or a server error.
    pub fn retryable(&self) -> bool {
        matches!(self, Error::Api { status, .. } if *status == 0 || *status == 429 || *status >= 500)
    }

    pub(crate) fn unreachable(err: impl fmt::Display) -> Self {
        Error::Api {
            status: 0,
            name: "application_error".into(),
            message: format!("Unable to reach the API: {err}"),
        }
    }
}

/// `Result` with this crate's [`Error`].
pub type Result<T, E = Error> = std::result::Result<T, E>;