Skip to main content

jev/
error.rs

1//! The crate's single error type.
2
3use crate::util::truncate_on_char_boundary;
4
5/// Maximum number of bytes of an API error body kept for diagnostics.
6const MAX_ERROR_BODY_BYTES: usize = 4096;
7
8/// Everything that can go wrong calling Jev, in one non-exhaustive enum.
9///
10/// Variants are chosen so callers can act on the *kind* of failure without parsing
11/// error strings: [`Error::is_retryable`] and [`Error::status`] cover the two most
12/// common branches (back off and try again, or surface the HTTP status).
13///
14/// No variant embeds request `state` or question criteria text: those may contain
15/// PII and are never placed in an error message or a `tracing` field.
16///
17/// # Examples
18///
19/// ```
20/// use jev::Error;
21///
22/// let err = Error::RateLimited { retry_after_secs: Some(2) };
23/// assert!(err.is_retryable());
24/// assert_eq!(err.status(), Some(429));
25/// ```
26#[derive(Debug, thiserror::Error)]
27#[non_exhaustive]
28pub enum Error {
29    /// The underlying HTTP transport failed (connect, timeout, TLS, decoding, ...).
30    #[error("request failed: {0}")]
31    Http(#[from] reqwest::Error),
32
33    /// Reading a case file (see [`crate::CaseSet::from_file`]) failed.
34    #[error("io error: {0}")]
35    Io(#[from] std::io::Error),
36
37    /// The API responded with a non-2xx status carrying a `{"error": {...}}` envelope.
38    #[error("API error (HTTP {status}): {message}")]
39    Api {
40        /// HTTP status code returned by the API.
41        status: u16,
42        /// Human-readable message extracted from the error envelope, if present.
43        message: String,
44        /// Raw response body, truncated to 4 KiB on a UTF-8 character boundary.
45        body: String,
46    },
47
48    /// HTTP 429. Split out because callers back off rather than fail.
49    #[error("rate limited (HTTP 429), retry after {retry_after_secs:?}s")]
50    RateLimited {
51        /// Seconds to wait before retrying, parsed from `Retry-After`, when present.
52        retry_after_secs: Option<u64>,
53    },
54
55    /// HTTP 402. Split out because callers stop rather than back off.
56    #[error("insufficient credits (HTTP 402): {message}")]
57    InsufficientCredits {
58        /// Human-readable message extracted from the error envelope, if present.
59        message: String,
60    },
61
62    /// The response body did not match the expected shape.
63    #[error("failed to parse response: {0}")]
64    Parse(String),
65
66    /// A [`crate::typed::Decision`] field had no corresponding entry in the answer map.
67    #[error("missing answer for question `{key}`")]
68    MissingAnswer {
69        /// The question key that was expected but absent.
70        key: String,
71    },
72
73    /// A question answer had the wrong primitive type for the accessor used.
74    #[error("question `{key}`: expected {expected} answer, got {actual}")]
75    AnswerType {
76        /// The question key being read.
77        key: String,
78        /// The primitive the caller expected (`"noul"`, `"choice"`, or `"score"`).
79        expected: &'static str,
80        /// The primitive actually present, or `"other(<type>)"` for an unknown one.
81        actual: String,
82    },
83
84    /// A `choice` answer named an option outside the caller's [`crate::typed::ChoiceOptions`].
85    #[error("question `{key}`: unknown choice `{choice}` (expected one of {expected})")]
86    UnknownChoice {
87        /// The question key being read.
88        key: String,
89        /// The option key the server returned.
90        choice: String,
91        /// A comma-separated list of the option keys the caller declared.
92        expected: String,
93    },
94
95    /// A `score` answer fell outside `0.0..=(levels - 1)` for the caller's
96    /// [`crate::typed::ScoreLevels`].
97    #[error("question `{key}`: score {score} out of range for {levels} levels")]
98    ScoreRange {
99        /// The question key being read.
100        key: String,
101        /// The out-of-range score returned by the server.
102        score: f64,
103        /// The number of levels the caller's enum declares.
104        levels: usize,
105    },
106
107    /// A caller-supplied value failed validation before it reached the network.
108    #[error("invalid {field}: {reason}")]
109    Invalid {
110        /// The name of the field or configuration key that failed validation.
111        field: String,
112        /// A human-readable reason, safe to log (never echoes the offending value
113        /// when the value itself might be sensitive).
114        reason: String,
115    },
116
117    /// The serialized state exceeded the model's estimated context window.
118    #[error("state too large: ~{estimated} tokens exceeds {limit}")]
119    StateTooLarge {
120        /// The estimated token count of the serialized request.
121        estimated: usize,
122        /// The model's context window, in tokens.
123        limit: usize,
124    },
125
126    /// No API key was configured for the selected provider.
127    #[error(
128        "no API key configured (set JEV_API_KEY or the selected provider's OPENROUTER_API_KEY / \
129         TYPESAFE_API_KEY)"
130    )]
131    MissingApiKey,
132
133    /// The overall per-request deadline elapsed, including any retries.
134    #[error("request timed out after {elapsed_ms}ms")]
135    Timeout {
136        /// Milliseconds elapsed before the deadline fired.
137        elapsed_ms: u64,
138    },
139}
140
141impl Error {
142    /// Builds an [`Error::Api`] (or the more specific [`Error::RateLimited`] /
143    /// [`Error::InsufficientCredits`]) from a status code and raw response body.
144    ///
145    /// The body is parsed as `{"error": {"message": ..., ...}}` on a best-effort basis;
146    /// a body that does not match the envelope still produces a usable error with the
147    /// raw text kept (truncated) for diagnostics.
148    pub(crate) fn from_api_response(
149        status: u16,
150        body: &str,
151        retry_after_secs: Option<u64>,
152    ) -> Self {
153        let truncated = truncate_on_char_boundary(body, MAX_ERROR_BODY_BYTES).to_string();
154        let message = parse_error_message(body).unwrap_or_else(|| truncated.clone());
155
156        match status {
157            402 => Error::InsufficientCredits { message },
158            429 => Error::RateLimited { retry_after_secs },
159            _ => Error::Api {
160                status,
161                message,
162                body: truncated,
163            },
164        }
165    }
166
167    /// Whether retrying the request that produced this error could plausibly succeed.
168    ///
169    /// Deterministic client errors (`400`, `401`, `402`, `403`, `404`, `413`, and any
170    /// caller-side validation failure) are never retryable; transport-level timeouts,
171    /// `429`, and `5xx` are.
172    ///
173    /// # Examples
174    ///
175    /// ```
176    /// use jev::Error;
177    ///
178    /// assert!(Error::RateLimited { retry_after_secs: None }.is_retryable());
179    /// assert!(!Error::InsufficientCredits { message: "no credits".into() }.is_retryable());
180    /// ```
181    #[must_use]
182    pub fn is_retryable(&self) -> bool {
183        match self {
184            Error::Api { status, .. } => is_retryable_status(*status),
185            Error::Http(e) => e.is_timeout() || e.is_connect() || e.is_request(),
186            Error::RateLimited { .. } | Error::Timeout { .. } => true,
187            Error::InsufficientCredits { .. }
188            | Error::Parse(_)
189            | Error::MissingAnswer { .. }
190            | Error::AnswerType { .. }
191            | Error::UnknownChoice { .. }
192            | Error::ScoreRange { .. }
193            | Error::Invalid { .. }
194            | Error::StateTooLarge { .. }
195            | Error::MissingApiKey
196            | Error::Io(_) => false,
197        }
198    }
199
200    /// The HTTP status code this error carries, when it originated from the API.
201    ///
202    /// # Examples
203    ///
204    /// ```
205    /// use jev::Error;
206    ///
207    /// assert_eq!(Error::RateLimited { retry_after_secs: None }.status(), Some(429));
208    /// assert_eq!(Error::MissingApiKey.status(), None);
209    /// ```
210    #[must_use]
211    pub fn status(&self) -> Option<u16> {
212        match self {
213            Error::Api { status, .. } => Some(*status),
214            Error::RateLimited { .. } => Some(429),
215            Error::InsufficientCredits { .. } => Some(402),
216            Error::Http(e) => e.status().map(|s| s.as_u16()),
217            _ => None,
218        }
219    }
220}
221
222/// Status codes the client retries: transient rate limiting and upstream failures.
223pub(crate) fn is_retryable_status(status: u16) -> bool {
224    matches!(status, 429 | 500 | 502 | 503 | 504)
225}
226
227/// Best-effort extraction of `error.message` from a `{"error": {...}}` envelope.
228fn parse_error_message(body: &str) -> Option<String> {
229    let value: serde_json::Value = serde_json::from_str(body).ok()?;
230    value
231        .get("error")?
232        .get("message")?
233        .as_str()
234        .map(str::to_string)
235}
236
237#[cfg(test)]
238mod tests {
239    use rstest::rstest;
240
241    use super::*;
242
243    #[test]
244    fn test_should_parse_error_envelope_message() {
245        let body = r#"{"error":{"code":400,"message":"bad request"}}"#;
246        let err = Error::from_api_response(400, body, None);
247        match err {
248            Error::Api {
249                status,
250                message,
251                body,
252            } => {
253                assert_eq!(status, 400);
254                assert_eq!(message, "bad request");
255                assert!(body.contains("bad request"));
256            }
257            other => panic!("expected Api variant, got {other:?}"),
258        }
259    }
260
261    #[test]
262    fn test_should_fall_back_to_raw_body_when_envelope_missing() {
263        let err = Error::from_api_response(500, "upstream exploded", None);
264        match err {
265            Error::Api { message, .. } => assert_eq!(message, "upstream exploded"),
266            other => panic!("expected Api variant, got {other:?}"),
267        }
268    }
269
270    #[test]
271    fn test_should_map_402_to_insufficient_credits() {
272        let body = r#"{"error":{"message":"top up your account"}}"#;
273        let err = Error::from_api_response(402, body, None);
274        assert!(matches!(err, Error::InsufficientCredits { .. }));
275        assert_eq!(err.status(), Some(402));
276        assert!(!err.is_retryable());
277    }
278
279    #[test]
280    fn test_should_map_429_to_rate_limited_with_retry_after() {
281        let err = Error::from_api_response(429, "{}", Some(3));
282        match err {
283            Error::RateLimited { retry_after_secs } => assert_eq!(retry_after_secs, Some(3)),
284            other => panic!("expected RateLimited variant, got {other:?}"),
285        }
286        assert!(err.is_retryable());
287    }
288
289    #[test]
290    fn test_should_truncate_long_error_body_on_char_boundary() {
291        let body = "€".repeat(4000); // 3 bytes each => 12000 bytes.
292        let err = Error::from_api_response(500, &body, None);
293        match err {
294            Error::Api {
295                body: truncated, ..
296            } => {
297                assert!(truncated.len() <= MAX_ERROR_BODY_BYTES);
298                // Must still be valid UTF-8 (guaranteed by type) and a true prefix.
299                assert!(body.starts_with(&truncated));
300            }
301            other => panic!("expected Api variant, got {other:?}"),
302        }
303    }
304
305    #[rstest]
306    #[case(400, false)]
307    #[case(401, false)]
308    #[case(402, false)]
309    #[case(403, false)]
310    #[case(404, false)]
311    #[case(413, false)]
312    #[case(429, true)]
313    #[case(500, true)]
314    #[case(502, true)]
315    #[case(503, true)]
316    #[case(504, true)]
317    fn test_should_classify_status_retryability(#[case] status: u16, #[case] retryable: bool) {
318        assert_eq!(is_retryable_status(status), retryable);
319    }
320
321    #[test]
322    fn test_should_not_retry_invalid_or_parse_errors() {
323        assert!(
324            !Error::Invalid {
325                field: "x".into(),
326                reason: "y".into()
327            }
328            .is_retryable()
329        );
330        assert!(!Error::Parse("bad".into()).is_retryable());
331        assert!(!Error::MissingApiKey.is_retryable());
332    }
333}