Skip to main content

typesafeai_sdk/
error.rs

1//! Error types for the TypeSafe SDK.
2//!
3//! Mirrors the error hierarchy in the Python and JavaScript SDKs:
4//! a root [`TypeSafeError`] struct wrapping an [`ErrorKind`] enum, with an
5//! optional request ID for correlating with server-side logs.
6
7use std::time::Duration;
8
9use thiserror::Error;
10
11/// The specific kind of error that occurred.
12///
13/// This is the inner classification extracted from [`TypeSafeError`]. Match
14/// on `err.kind()` to handle specific error categories.
15#[derive(Debug, Error)]
16#[non_exhaustive]
17pub enum ErrorKind {
18    /// `401 Unauthorized` — missing or invalid API key.
19    #[error("authentication failed: {0}")]
20    Authentication(String),
21
22    /// `400 Bad Request` — the server rejected the request as malformed.
23    #[error("bad request: {0}")]
24    BadRequest(String),
25
26    /// `404 Not Found` — the requested resource does not exist.
27    #[error("not found: {0}")]
28    NotFound(String),
29
30    /// `422 Unprocessable Entity` — the request body failed validation.
31    #[error("unprocessable entity: {0}")]
32    UnprocessableEntity(String),
33
34    /// `429 Too Many Requests` — rate limit exceeded.
35    #[error("rate limit exceeded: {0}")]
36    RateLimit(String),
37
38    /// `500`, `502`, `503`, or `504` — retryable server-side error.
39    #[error("internal server error: {0}")]
40    InternalServer(String),
41
42    /// `529 Overloaded` — the service is temporarily overloaded.
43    #[error("service overloaded: {0}")]
44    Overloaded(String),
45
46    /// `408 Request Timeout` — the server timed out waiting for the request.
47    /// This is a server-side timeout, distinct from the client-side
48    /// [`Timeout`](Self::Timeout) which carries the configured duration.
49    #[error("request timeout: {0}")]
50    RequestTimeout(String),
51
52    /// A generic API error for unexpected HTTP status codes.
53    ///
54    /// This includes 3xx redirect responses — the SDK's default HTTP client
55    /// disables redirects (via `reqwest::redirect::Policy::none()`) to
56    /// prevent POST body replay on 307/308. If you supply a custom
57    /// `reqwest::Client` that follows redirects, 3xx responses will not
58    /// appear here because reqwest follows them automatically.
59    #[error("API error (status {status}): {message}")]
60    Api {
61        /// The HTTP status code.
62        status: u16,
63        /// The error message from the server.
64        message: String,
65    },
66
67    /// The request could not connect or timed out after all retries.
68    #[error("connection error: {0}")]
69    Connection(String),
70
71    /// The request timed out.
72    #[error("request timed out (configured timeout: {0:?})")]
73    Timeout(Duration),
74
75    /// The response body did not match the expected schema.
76    #[error("response validation error: {message}{}", field_path.as_ref().map(|p| format!(" (field: {p})")).unwrap_or_default())]
77    ResponseValidation {
78        /// The human-readable error message.
79        message: String,
80        /// The JSON path to the field that failed validation (e.g.
81        /// `answers.billing.noul`), if known.
82        field_path: Option<String>,
83    },
84
85    /// A local validation error before the request was sent
86    /// (e.g. empty questions or a score with fewer than two criteria).
87    #[error("{0}")]
88    Validation(String),
89
90    /// A JSON serialization or deserialization error.
91    #[error("JSON error: {0}")]
92    Json(#[from] serde_json::Error),
93
94    /// An HTTP transport error from the underlying client (e.g. a body-read
95    /// failure, redirect loop, or request-builder error). The underlying
96    /// `reqwest::Error` is converted to a string so it does not leak into
97    /// the public API.
98    #[error("transport error: {0}")]
99    Transport(String),
100
101    /// A Tokio runtime error from the blocking client (e.g. attempting to
102    /// create or use a blocking client from inside an async context).
103    #[error("runtime error: {0}")]
104    Runtime(String),
105}
106
107impl ErrorKind {
108    /// Returns `true` if this error is retryable (rate limit, overload,
109    /// server error, request timeout, connection failure, or client
110    /// timeout).
111    ///
112    /// `Transport` errors (body read, builder, redirect, decode) are
113    /// deterministic or occur after the server has already processed the
114    /// request, and are **not** retryable.
115    pub fn is_retryable(&self) -> bool {
116        matches!(
117            self,
118            ErrorKind::RateLimit(_)
119                | ErrorKind::RequestTimeout(_)
120                | ErrorKind::Overloaded(_)
121                | ErrorKind::InternalServer(_)
122                | ErrorKind::Connection(_)
123                | ErrorKind::Timeout(_)
124        )
125    }
126}
127
128/// The root error type returned by all SDK operations.
129///
130/// Wraps an [`ErrorKind`] with an optional request ID (from the
131/// `x-typesafe-request-id` response header) for correlating errors with
132/// server-side logs.
133#[derive(Debug)]
134#[non_exhaustive]
135pub struct TypeSafeError {
136    kind: ErrorKind,
137    request_id: Option<String>,
138}
139
140impl TypeSafeError {
141    /// Create a new error from a kind, with no request ID.
142    pub fn new(kind: ErrorKind) -> Self {
143        Self {
144            kind,
145            request_id: None,
146        }
147    }
148
149    /// Create a new error from a kind and an optional request ID.
150    pub fn with_request_id(kind: ErrorKind, request_id: Option<String>) -> Self {
151        Self { kind, request_id }
152    }
153
154    /// Returns the specific error kind.
155    pub fn kind(&self) -> &ErrorKind {
156        &self.kind
157    }
158
159    /// Returns the request ID associated with this error, if the server
160    /// provided one via the `x-typesafe-request-id` header.
161    pub fn request_id(&self) -> Option<&str> {
162        self.request_id.as_deref()
163    }
164
165    /// Returns `true` if this error is retryable. Delegates to
166    /// [`ErrorKind::is_retryable`].
167    pub fn is_retryable(&self) -> bool {
168        self.kind.is_retryable()
169    }
170}
171
172impl std::fmt::Display for TypeSafeError {
173    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174        write!(f, "{}", self.kind)?;
175        if let Some(ref id) = self.request_id {
176            write!(f, " (request id: {id})")?;
177        }
178        Ok(())
179    }
180}
181
182impl std::error::Error for TypeSafeError {}
183
184impl From<serde_json::Error> for TypeSafeError {
185    fn from(e: serde_json::Error) -> Self {
186        Self::new(ErrorKind::Json(e))
187    }
188}
189
190impl From<ErrorKind> for TypeSafeError {
191    fn from(kind: ErrorKind) -> Self {
192        Self::new(kind)
193    }
194}
195
196/// A convenience `Result` alias used throughout the SDK.
197pub type Result<T> = std::result::Result<T, TypeSafeError>;
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn response_validation_with_field_path() {
205        let err = TypeSafeError::new(ErrorKind::ResponseValidation {
206            message: "expected a number".to_string(),
207            field_path: Some("answers.billing.noul".to_string()),
208        });
209        let display = format!("{err}");
210        assert!(display.contains("expected a number"));
211        assert!(display.contains("answers.billing.noul"));
212    }
213
214    #[test]
215    fn response_validation_without_field_path() {
216        let err = TypeSafeError::new(ErrorKind::ResponseValidation {
217            message: "malformed JSON".to_string(),
218            field_path: None,
219        });
220        let display = format!("{err}");
221        assert!(display.contains("malformed JSON"));
222        assert!(!display.contains("field:"));
223    }
224
225    #[test]
226    fn response_validation_is_not_retryable() {
227        let kind = ErrorKind::ResponseValidation {
228            message: "bad".to_string(),
229            field_path: None,
230        };
231        assert!(!kind.is_retryable());
232    }
233
234    #[test]
235    fn request_id_displayed_when_present() {
236        let err = TypeSafeError::with_request_id(
237            ErrorKind::Authentication("bad key".to_string()),
238            Some("req-123".to_string()),
239        );
240        let display = format!("{err}");
241        assert!(display.contains("bad key"));
242        assert!(display.contains("req-123"));
243    }
244
245    #[test]
246    fn request_id_absent_when_not_provided() {
247        let err = TypeSafeError::new(ErrorKind::Authentication("bad key".to_string()));
248        let display = format!("{err}");
249        assert!(display.contains("bad key"));
250        assert!(!display.contains("request id"));
251    }
252
253    #[test]
254    fn from_error_kind_creates_error() {
255        let kind = ErrorKind::Validation("test".to_string());
256        let err: TypeSafeError = kind.into();
257        assert!(matches!(err.kind(), ErrorKind::Validation(_)));
258    }
259}