openapi-nexus 0.2.2

OpenAPI 3.x multi-language code generator
Documentation
use std::fmt;

/// Error types for the generated SDK.
#[derive(Debug)]
pub enum Error {
    /// HTTP transport error.
    Http(ureq::Error),
    /// I/O error while reading response body.
    Io(std::io::Error),
    /// JSON deserialization error.
    Deserialize(serde_json::Error),
    /// XML serialization error.
    Xml(serde_xml_rs::Error),
    /// Unsupported generated operation.
    Unsupported(&'static str),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Http(e) => write!(f, "HTTP error: {e}"),
            Error::Io(e) => write!(f, "IO error: {e}"),
            Error::Deserialize(e) => write!(f, "Deserialization error: {e}"),
            Error::Xml(e) => write!(f, "XML serialization error: {e}"),
            Error::Unsupported(e) => write!(f, "Unsupported operation: {e}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Http(e) => Some(e),
            Error::Io(e) => Some(e),
            Error::Deserialize(e) => Some(e),
            Error::Xml(e) => Some(e),
            Error::Unsupported(_) => None,
        }
    }
}

impl From<ureq::Error> for Error {
    fn from(e: ureq::Error) -> Self {
        Error::Http(e)
    }
}

impl From<serde_json::Error> for Error {
    fn from(e: serde_json::Error) -> Self {
        Error::Deserialize(e)
    }
}

impl From<serde_xml_rs::Error> for Error {
    fn from(e: serde_xml_rs::Error) -> Self {
        Error::Xml(e)
    }
}

/// Typed HTTP error response payload.
#[derive(Debug)]
pub struct ApiError<T> {
    status_code: u16,
    headers: ureq::http::HeaderMap,
    raw_body: Vec<u8>,
    body: Result<T, Error>,
}

impl<T> ApiError<T> {
    pub fn new(
        status_code: u16,
        headers: ureq::http::HeaderMap,
        raw_body: Vec<u8>,
        body: Result<T, Error>,
    ) -> Self {
        Self {
            status_code,
            headers,
            raw_body,
            body,
        }
    }

    pub fn status_code(&self) -> u16 {
        self.status_code
    }

    pub fn headers(&self) -> &ureq::http::HeaderMap {
        &self.headers
    }

    pub fn raw_body(&self) -> &[u8] {
        &self.raw_body
    }

    pub fn body(&self) -> Result<&T, &Error> {
        self.body.as_ref()
    }
}