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
74// ── Tests ─────────────────────────────────────────────────────────────────────
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79
80 /// `LlmError::ApiError` formats the status code and body in the display string.
81 ///
82 /// Why: Consumers and logs rely on the `Display` impl; verify it contains
83 /// the key fields.
84 /// What: Construct an `ApiError`, call `to_string()`, assert substrings.
85 /// Test: this test.
86 #[test]
87 fn api_error_display_includes_status_and_body() {
88 let err = LlmError::ApiError {
89 status: 429,
90 body: "rate limited".into(),
91 };
92 let s = err.to_string();
93 assert!(s.contains("429"), "status missing from: {s}");
94 assert!(s.contains("rate limited"), "body missing from: {s}");
95 }
96
97 /// `LlmError::MissingConfig` carries the field name in its display.
98 ///
99 /// Why: Operator experience — the error should tell them exactly which
100 /// configuration field to set.
101 /// What: Construct a `MissingConfig`, assert the key name appears.
102 /// Test: this test.
103 #[test]
104 fn missing_config_display_includes_field_name() {
105 let err = LlmError::MissingConfig("OPENROUTER_API_KEY".into());
106 let s = err.to_string();
107 assert!(s.contains("OPENROUTER_API_KEY"), "field name missing: {s}");
108 }
109
110 /// `LlmError::Bedrock` carries the SDK error text verbatim in its display.
111 ///
112 /// Why: Operators debugging a Bedrock failure need the underlying SDK
113 /// message (auth, validation, throttling) surfaced unchanged.
114 /// What: Construct a `Bedrock` error, assert the message appears.
115 /// Test: this test.
116 #[test]
117 fn bedrock_error_display_includes_message() {
118 let err = LlmError::Bedrock("ValidationException: bad model id".into());
119 let s = err.to_string();
120 assert!(s.contains("ValidationException"), "message missing: {s}");
121 }
122
123 /// `LlmError::Deserialise` includes both the error and the body.
124 ///
125 /// Why: Debugging a deserialisation failure requires seeing the raw JSON
126 /// body; confirm it appears in the display.
127 /// What: Construct a deserialise error from a real `serde_json` error.
128 /// Test: this test.
129 #[test]
130 fn deserialise_error_includes_body() {
131 let raw = "{invalid json}";
132 let serde_err = serde_json::from_str::<serde_json::Value>(raw).unwrap_err();
133 let err = LlmError::Deserialise {
134 source: serde_err,
135 body: raw.into(),
136 };
137 let s = err.to_string();
138 assert!(s.contains(raw), "raw body missing: {s}");
139 }
140}