bibby 0.2.0

The official Rust SDK for Bytebury — typed clients, smart .env initialization, and ergonomic macros for Geo, Images, PDF, Mailer, Uploader, Cron, Forms, Webhooks, Monitors, and Vault.
Documentation
//! Error types returned by the Bytebury SDK.

use serde::Deserialize;

/// A specialized [`Result`](std::result::Result) type for Bytebury SDK operations.
pub type Result<T> = std::result::Result<T, Error>;

/// Errors returned by the [`Bibby`](crate::Bibby) client and service helpers.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The API token environment variable (by default `BYTEBURY_API_TOKEN`) was
    /// not set or was empty when calling [`Bibby::init`](crate::Bibby::init).
    #[error(
        "missing Bytebury API token: set `{env_var}` in your environment or `.env` file (create a key at https://bytebury.com/api-keys)"
    )]
    MissingApiToken {
        /// The name of the environment variable that was checked.
        env_var: String,
    },

    /// The client configuration was invalid (for example, an empty API token or
    /// malformed base URL).
    #[error("invalid client configuration: {0}")]
    InvalidConfig(String),

    /// The Bytebury API responded with a non-2xx HTTP status code.
    #[error("Bytebury API error ({status}): {message}")]
    Api {
        /// HTTP status code returned by the API.
        status: u16,
        /// Human-readable error message from `{ "error": "..." }` or the raw body.
        message: String,
    },

    /// An underlying HTTP transport error occurred (connection failure, timeout, TLS, etc.).
    #[error("HTTP request failed: {0}")]
    Http(#[from] reqwest::Error),

    /// Failed to serialize a request body or deserialize a JSON response.
    #[error("JSON serialization error: {0}")]
    Json(#[from] serde_json::Error),

    /// Failed to decode a base64 payload (e.g., from an encoded image or rendered PDF).
    #[error("base64 decode error: {0}")]
    Base64(#[from] base64::DecodeError),

    /// An outgoing Bytebury webhook signature failed verification.
    #[error("webhook signature verification failed: {0}")]
    WebhookSignature(String),
}

impl Error {
    /// Returns the HTTP status code if this error came from a Bytebury API response.
    pub fn status(&self) -> Option<u16> {
        match self {
            Self::Api { status, .. } => Some(*status),
            Self::Http(err) => err.status().map(|s| s.as_u16()),
            _ => None,
        }
    }

    /// Returns `true` if the API responded with `400 Bad Request`.
    pub fn is_bad_request(&self) -> bool {
        self.status() == Some(400)
    }

    /// Returns `true` if the API responded with `401 Unauthorized`.
    pub fn is_unauthorized(&self) -> bool {
        self.status() == Some(401)
    }

    /// Returns `true` if the API responded with `403 Forbidden`.
    pub fn is_forbidden(&self) -> bool {
        self.status() == Some(403)
    }

    /// Returns `true` if the API responded with `404 Not Found`.
    pub fn is_not_found(&self) -> bool {
        self.status() == Some(404)
    }

    /// Returns `true` if the API responded with `409 Conflict`.
    pub fn is_conflict(&self) -> bool {
        self.status() == Some(409)
    }

    /// Returns `true` if the API responded with `413 Payload Too Large`.
    pub fn is_payload_too_large(&self) -> bool {
        self.status() == Some(413)
    }

    /// Returns `true` if the API responded with `429 Too Many Requests`.
    pub fn is_rate_limited(&self) -> bool {
        self.status() == Some(429)
    }
}

#[derive(Deserialize)]
pub(crate) struct ApiErrorBody {
    pub(crate) error: String,
}

pub(crate) fn parse_api_error(status: u16, body: &[u8]) -> Error {
    if let Ok(parsed) = serde_json::from_slice::<ApiErrorBody>(body) {
        return Error::Api {
            status,
            message: parsed.error,
        };
    }

    let fallback = String::from_utf8_lossy(body).trim().to_string();
    let message = if fallback.is_empty() {
        format!("HTTP {status}")
    } else {
        fallback
    };

    Error::Api { status, message }
}