Skip to main content

typesafe_ai/
error.rs

1use std::convert::Infallible;
2use std::time::Duration;
3
4use http::{HeaderMap, StatusCode};
5use thiserror::Error;
6
7/// Errors returned while configuring or using a client.
8#[derive(Debug, Error)]
9pub enum Error<E = Infallible> {
10    /// The request violates a documented API constraint.
11    #[error("request validation failed at {field}: {message}")]
12    Validation {
13        /// Field containing the invalid value.
14        field: String,
15        /// Description of the constraint.
16        message: String,
17    },
18    /// The client configuration is invalid.
19    #[error("invalid client configuration: {0}")]
20    Configuration(String),
21    /// The HTTP exchange failed before a response was available.
22    #[error("HTTP transport failed: {0}")]
23    Transport(#[source] E),
24    /// The configured per-attempt timeout elapsed.
25    #[error("HTTP attempt timed out (configured attempt limit: {timeout:?})")]
26    Timeout {
27        /// Timeout configured for each attempt.
28        timeout: Duration,
29    },
30    /// A successful HTTP response could not be decoded.
31    #[error("failed to decode successful HTTP {status} response: {source}")]
32    Decode {
33        /// HTTP status returned by the API.
34        status: StatusCode,
35        /// Value of the request id response header, when present.
36        request_id: Option<String>,
37        /// HTTP response headers.
38        headers: Box<HeaderMap>,
39        /// Raw response bytes.
40        body: Vec<u8>,
41        /// JSON decoding error.
42        #[source]
43        source: serde_json::Error,
44    },
45    /// The API returned a non-success status.
46    #[error("TypeSafe API returned HTTP {status} after {attempts} attempt(s)")]
47    Api {
48        /// HTTP status returned by the API.
49        status: StatusCode,
50        /// Value of the request id response header, when present.
51        request_id: Option<String>,
52        /// HTTP response headers.
53        headers: Box<HeaderMap>,
54        /// Raw response bytes, including non-JSON bodies.
55        body: Vec<u8>,
56        /// Requested server retry delay, when supplied and valid.
57        retry_after: Option<Duration>,
58        /// Total attempts made, including the initial request.
59        attempts: u64,
60    },
61    /// An application-supplied event sequence ended before a terminal event.
62    #[error("evaluation event sequence ended without a terminal result")]
63    IncompleteEvaluation,
64}
65
66impl<E> Error<E> {
67    /// Returns the associated HTTP status, when a response was received.
68    pub fn status(&self) -> Option<StatusCode> {
69        match self {
70            Self::Decode { status, .. } | Self::Api { status, .. } => Some(*status),
71            _ => None,
72        }
73    }
74
75    /// Returns the TypeSafe request id, when one was received.
76    pub fn request_id(&self) -> Option<&str> {
77        match self {
78            Self::Decode { request_id, .. } | Self::Api { request_id, .. } => request_id.as_deref(),
79            _ => None,
80        }
81    }
82
83    /// Returns raw response bytes for API and decode failures.
84    pub fn body(&self) -> Option<&[u8]> {
85        match self {
86            Self::Decode { body, .. } | Self::Api { body, .. } => Some(body),
87            _ => None,
88        }
89    }
90
91    /// Returns response headers for API and decode failures.
92    pub fn headers(&self) -> Option<&HeaderMap> {
93        match self {
94            Self::Decode { headers, .. } | Self::Api { headers, .. } => Some(headers.as_ref()),
95            _ => None,
96        }
97    }
98}
99
100impl Error<Infallible> {
101    /// Converts a backend-neutral error to one carrying a concrete transport error type.
102    ///
103    /// This is useful in custom client implementations after calling [`Request::validate`](crate::Request::validate).
104    pub fn with_transport<E>(self) -> Error<E>
105    where
106        E: std::error::Error + Send + Sync + 'static,
107    {
108        match self {
109            Self::Validation { field, message } => Error::Validation { field, message },
110            Self::Configuration(message) => Error::Configuration(message),
111            Self::Transport(never) => match never {},
112            Self::Timeout { timeout } => Error::Timeout { timeout },
113            Self::Decode {
114                status,
115                request_id,
116                headers,
117                body,
118                source,
119            } => Error::Decode {
120                status,
121                request_id,
122                headers,
123                body,
124                source,
125            },
126            Self::Api {
127                status,
128                request_id,
129                headers,
130                body,
131                retry_after,
132                attempts,
133            } => Error::Api {
134                status,
135                request_id,
136                headers,
137                body,
138                retry_after,
139                attempts,
140            },
141            Self::IncompleteEvaluation => Error::IncompleteEvaluation,
142        }
143    }
144}