Skip to main content

trusty_code/llm/
error.rs

1//! Error types for the LLM client.
2//!
3//! Why: Structured errors let callers pattern-match on failure modes (network
4//! error vs. API-level error vs. deserialisation failure) without parsing
5//! strings.
6//! What: `LlmError` covers the four failure categories the client can produce;
7//! it implements `std::error::Error` via `thiserror`.
8//! Test: `error::tests::*` — error display strings, `From` conversions.
9
10use thiserror::Error;
11
12/// Error type returned by `LlmClient` operations.
13///
14/// Why: Library code must expose structured errors rather than `anyhow::Error`
15/// so consumers can programmatically handle recoverable failures (e.g.
16/// rate-limit → retry, invalid API key → fast-fail).
17/// What: Covers network transport errors, non-200 HTTP responses with an
18/// optional API-level error body, and response deserialisation failures.
19/// Test: `llm_error_display`.
20#[derive(Debug, Error)]
21pub enum LlmError {
22    /// The HTTP transport layer failed (connection refused, TLS error, timeout).
23    ///
24    /// Why: Distinct from API errors so callers can apply retry logic to
25    /// transient network failures without retrying on e.g. invalid-key errors.
26    #[error("HTTP transport error: {0}")]
27    Transport(#[from] reqwest::Error),
28
29    /// The API returned a non-2xx status code.
30    ///
31    /// Why: Callers need both the status code and the raw body to decide
32    /// whether to retry (e.g. 429 Too Many Requests) or give up (e.g. 401
33    /// Unauthorized).
34    #[error("API error {status}: {body}")]
35    ApiError {
36        /// HTTP status code.
37        status: u16,
38        /// Raw response body (may be JSON or plain text).
39        body: String,
40    },
41
42    /// The response body could not be deserialised into `ChatResponse`.
43    ///
44    /// Why: Separates schema-mismatch problems (usually provider bugs or
45    /// version drift) from transport and API-level issues.
46    #[error("response deserialisation failed: {source}\nbody: {body}")]
47    Deserialise {
48        /// The underlying serde error.
49        source: serde_json::Error,
50        /// The raw body that failed to parse (aids debugging).
51        body: String,
52    },
53
54    /// A required configuration value is missing.
55    ///
56    /// Why: Failing at construction time with a clear message is better than
57    /// receiving a cryptic 401 from the API.
58    #[error("missing configuration: {0}")]
59    MissingConfig(String),
60
61    /// An AWS Bedrock Converse-API-level failure (#1021 phase 1): SDK
62    /// transport/auth/validation/throttling errors, or a request/response
63    /// shape the Converse transport could not build.
64    ///
65    /// Why: Bedrock errors arrive as `aws_sdk_bedrockruntime` SDK error types,
66    /// not `reqwest::Error` or an HTTP status code, so they don't fit
67    /// [`Self::Transport`] or [`Self::ApiError`]. Carrying the SDK's own
68    /// `Display` text (rather than inventing a fake status code) keeps the
69    /// error message honest.
70    #[error("Bedrock error: {0}")]
71    Bedrock(String),
72
73    /// A failure originating in the shared `trusty_common::inference` adapter
74    /// layer that does not map cleanly onto a status-carrying variant (#2406):
75    /// a transport error (the adapter stringifies `reqwest::Error` before it
76    /// reaches tcode, so it cannot be a [`Self::Transport`]), a response the
77    /// shared parser rejected, or a missing/unregistered-provider alarm. The
78    /// two shared errors that DO map cleanly — a non-2xx API status and a
79    /// missing credential — are translated to [`Self::ApiError`] and
80    /// [`Self::MissingConfig`] respectively (see `llm::convert::map_error`) so
81    /// their status code / operator guidance is preserved.
82    ///
83    /// Why: keeps the shared error's own `Display` text verbatim rather than
84    /// forcing a lossy re-shape into a status-carrying variant it does not fit.
85    #[error("inference error: {0}")]
86    Inference(String),
87}
88
89// ── Tests ─────────────────────────────────────────────────────────────────────
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94
95    /// `LlmError::ApiError` formats the status code and body in the display string.
96    ///
97    /// Why: Consumers and logs rely on the `Display` impl; verify it contains
98    /// the key fields.
99    /// What: Construct an `ApiError`, call `to_string()`, assert substrings.
100    /// Test: this test.
101    #[test]
102    fn api_error_display_includes_status_and_body() {
103        let err = LlmError::ApiError {
104            status: 429,
105            body: "rate limited".into(),
106        };
107        let s = err.to_string();
108        assert!(s.contains("429"), "status missing from: {s}");
109        assert!(s.contains("rate limited"), "body missing from: {s}");
110    }
111
112    /// `LlmError::MissingConfig` carries the field name in its display.
113    ///
114    /// Why: Operator experience — the error should tell them exactly which
115    /// configuration field to set.
116    /// What: Construct a `MissingConfig`, assert the key name appears.
117    /// Test: this test.
118    #[test]
119    fn missing_config_display_includes_field_name() {
120        let err = LlmError::MissingConfig("OPENROUTER_API_KEY".into());
121        let s = err.to_string();
122        assert!(s.contains("OPENROUTER_API_KEY"), "field name missing: {s}");
123    }
124
125    /// `LlmError::Bedrock` carries the SDK error text verbatim in its display.
126    ///
127    /// Why: Operators debugging a Bedrock failure need the underlying SDK
128    /// message (auth, validation, throttling) surfaced unchanged.
129    /// What: Construct a `Bedrock` error, assert the message appears.
130    /// Test: this test.
131    #[test]
132    fn bedrock_error_display_includes_message() {
133        let err = LlmError::Bedrock("ValidationException: bad model id".into());
134        let s = err.to_string();
135        assert!(s.contains("ValidationException"), "message missing: {s}");
136    }
137
138    /// `LlmError::Deserialise` includes both the error and the body.
139    ///
140    /// Why: Debugging a deserialisation failure requires seeing the raw JSON
141    /// body; confirm it appears in the display.
142    /// What: Construct a deserialise error from a real `serde_json` error.
143    /// Test: this test.
144    #[test]
145    fn deserialise_error_includes_body() {
146        let raw = "{invalid json}";
147        let serde_err = serde_json::from_str::<serde_json::Value>(raw).unwrap_err();
148        let err = LlmError::Deserialise {
149            source: serde_err,
150            body: raw.into(),
151        };
152        let s = err.to_string();
153        assert!(s.contains(raw), "raw body missing: {s}");
154    }
155}