1use alloc::{boxed::Box, string::String, string::ToString, vec::Vec};
2use core::{fmt, time::Duration};
3
4use serde::Deserialize;
5
6#[derive(Debug, thiserror::Error)]
11#[non_exhaustive]
12pub enum Error {
13 #[error("at least one question is required")]
15 NoQuestions,
16 #[error("duplicate question id: {0}")]
18 DuplicateId(String),
19 #[error("invalid criteria for {id:?}: {reason}")]
21 InvalidCriteria {
22 id: Option<String>,
26 reason: &'static str,
28 },
29 #[error("the client configuration is invalid: {reason}")]
31 Config {
32 reason: String,
34 },
35 #[error("authentication failed (HTTP {status}): {detail}")]
37 Auth {
38 status: u16,
40 detail: ErrorDetail,
42 },
43 #[error("bad request (HTTP {status}): {detail}")]
45 BadRequest {
46 status: u16,
48 detail: ErrorDetail,
50 },
51 #[error("rate limited (HTTP 429): {detail}")]
53 RateLimited {
54 retry_after: Option<Duration>,
56 detail: ErrorDetail,
58 },
59 #[error("service overloaded (HTTP 529): {detail}")]
61 Overloaded {
62 detail: ErrorDetail,
64 },
65 #[error("HTTP {status}: {detail}")]
67 Http {
68 status: u16,
70 detail: ErrorDetail,
72 },
73 #[error("protocol error for {id:?}: {reason}")]
75 Protocol {
76 id: Option<String>,
78 reason: String,
80 },
81 #[error(transparent)]
83 Json(#[from] serde_json::Error),
84 #[error("transport error: {0}")]
86 Transport(#[source] Box<dyn core::error::Error + Send + Sync>),
87}
88
89#[derive(Debug, Eq, PartialEq)]
94pub struct ErrorDetail {
95 pub error_type: Option<String>,
97 pub message: Option<String>,
99 pub request_id: Option<String>,
101 pub raw: String,
103}
104
105impl ErrorDetail {
106 #[must_use]
116 pub fn parse(body: &[u8], request_id: Option<&str>) -> Self {
117 let raw = String::from_utf8_lossy(body).into_owned();
118
119 if let Ok(body) = serde_json::from_slice::<ObjectBody>(body) {
120 return Self::new(raw, request_id, body.detail.error_type, body.detail.message);
121 }
122 if let Ok(body) = serde_json::from_slice::<StringBody>(body) {
123 return Self::new(raw, request_id, None, Some(body.detail));
124 }
125 if let Ok(body) = serde_json::from_slice::<PydanticBody>(body) {
126 return Self::new(raw, request_id, None, Some(body.message()));
127 }
128
129 Self::new(raw, request_id, None, None)
130 }
131
132 fn new(
133 raw: String,
134 request_id: Option<&str>,
135 error_type: Option<String>,
136 message: Option<String>,
137 ) -> Self {
138 Self {
139 error_type,
140 message,
141 request_id: request_id.map(String::from),
142 raw,
143 }
144 }
145}
146
147impl fmt::Display for ErrorDetail {
148 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
149 match (&self.error_type, &self.message) {
150 (Some(error_type), Some(message)) => write!(formatter, "{error_type}: {message}")?,
151 (Some(error_type), None) => error_type.fmt(formatter)?,
152 (None, Some(message)) => message.fmt(formatter)?,
153 (None, None) => formatter.write_str("unknown API error")?,
154 }
155 if let Some(request_id) = &self.request_id {
156 write!(formatter, " (request_id: {request_id})")?;
157 }
158 Ok(())
159 }
160}
161
162#[must_use]
177pub fn classify(
178 status: u16,
179 body: &[u8],
180 retry_after: Option<Duration>,
181 request_id: Option<&str>,
182) -> Error {
183 let detail = ErrorDetail::parse(body, request_id);
184 match status {
185 401 | 403 => Error::Auth { status, detail },
186 400 | 422 => Error::BadRequest { status, detail },
187 429 => Error::RateLimited {
188 retry_after,
189 detail,
190 },
191 529 => Error::Overloaded { detail },
192 _ => Error::Http { status, detail },
193 }
194}
195
196#[derive(Deserialize)]
197struct ObjectBody {
198 detail: ObjectDetail,
199}
200
201#[derive(Deserialize)]
202struct ObjectDetail {
203 error_type: Option<String>,
204 message: Option<String>,
205}
206
207#[derive(Deserialize)]
208struct StringBody {
209 detail: String,
210}
211
212#[derive(Deserialize)]
213struct PydanticBody {
214 detail: Vec<PydanticEntry>,
215}
216
217impl PydanticBody {
218 fn message(self) -> String {
219 let mut message = String::new();
220 for (entry_index, entry) in self.detail.into_iter().enumerate() {
221 if entry_index != 0 {
222 message.push_str("; ");
223 }
224 for (location_index, location) in entry.loc.into_iter().enumerate() {
225 if location_index != 0 {
226 message.push('.');
227 }
228 match location {
229 Location::Text(value) => message.push_str(&value),
230 Location::Index(value) => message.push_str(&value.to_string()),
231 }
232 }
233 message.push_str(": ");
234 message.push_str(&entry.msg);
235 }
236 message
237 }
238}
239
240#[derive(Deserialize)]
241struct PydanticEntry {
242 loc: Vec<Location>,
243 msg: String,
244}
245
246#[derive(Deserialize)]
247#[serde(untagged)]
248enum Location {
249 Text(String),
250 Index(u64),
251}
252
253#[cfg(test)]
254mod tests {
255 use alloc::string::ToString;
256 use core::time::Duration;
257
258 use super::{Error, ErrorDetail, classify};
259
260 mod fixtures {
261 pub const BAD_REQUEST_OBJECT: &str =
262 r#"{"detail":{"error_type":"api_usage_error","message":"Invalid request."}}"#;
263 pub const CHOICE_EMPTY: &str =
264 r#"{"detail":"Choice question must have at least one choice: q"}"#;
265 pub const CHOICE_TOO_LARGE: &str =
266 r#"{"detail":"Too many choices. Must have at most 255 choices."}"#;
267 pub const SCORE_TOO_LARGE: &str =
268 r#"{"detail":"Too many score levels. Must have at most 10 levels."}"#;
269 pub const NOUL_EMPTY: &str =
270 r#"{"detail":"Noul question must have criteria or instructions: q"}"#;
271 pub const INVALID_KEY: &str = r#"{"detail":{"error_type":"authentication_error","message":"Cannot authenticate with the server. Please check your API key and try again."}}"#;
272 pub const MISSING_KEY: &str = r#"{"detail":{"error_type":"authentication_error","message":"Must supply an API key! Check your request and try again."}}"#;
273 pub const EMPTY_QUESTIONS: &str = r#"{"detail":[{"type":"too_short","loc":["body","questions"],"msg":"Dictionary should have at least 1 item after validation, not 0","input":{},"ctx":{"field_type":"Dictionary","min_length":1,"actual_length":0}}]}"#;
274 pub const EMPTY_SCORE: &str = r#"{"detail":[{"type":"too_short","loc":["body","questions","q","score","criteria"],"msg":"List should have at least 1 item after validation, not 0","input":[],"ctx":{"field_type":"List","min_length":1,"actual_length":0}}]}"#;
275 pub const MISSING_MODEL: &str = r#"{"detail":[{"type":"missing","loc":["body","model"],"msg":"Field required","input":{"state":"x","questions":{"q":{"type":"noul","instructions":"is it?"}}}}]}"#;
276 pub const NOT_FOUND: &str = r#"{"detail":"Not Found"}"#;
277 }
278
279 fn assert_detail(
280 detail: &ErrorDetail,
281 body: &str,
282 error_type: Option<&str>,
283 message: Option<&str>,
284 ) {
285 assert_eq!(detail.error_type.as_deref(), error_type);
286 assert_eq!(detail.message.as_deref(), message);
287 assert_eq!(detail.request_id.as_deref(), Some("req_deadbeef"));
288 assert_eq!(detail.raw, body);
289 }
290
291 fn assert_http_parts(
292 error: &Error,
293 status: u16,
294 detail: &ErrorDetail,
295 body: &str,
296 error_type: Option<&str>,
297 message: Option<&str>,
298 ) {
299 assert_detail(detail, body, error_type, message);
300 let displayed = error.to_string();
301 assert!(displayed.contains(&status.to_string()));
302 if let Some(error_type) = error_type {
303 assert!(displayed.contains(error_type));
304 }
305 if let Some(message) = message {
306 assert!(displayed.contains(message));
307 }
308 assert!(displayed.contains("req_deadbeef"));
309 }
310
311 fn assert_bad_request(status: u16, body: &str, error_type: Option<&str>, message: &str) {
312 let error = classify(status, body.as_bytes(), None, Some("req_deadbeef"));
313 let Error::BadRequest { status, detail } = &error else {
314 panic!("expected BadRequest, got {error:?}");
315 };
316 assert_http_parts(&error, *status, detail, body, error_type, Some(message));
317 }
318
319 fn assert_auth(status: u16, body: &str, message: &str) {
320 let error = classify(status, body.as_bytes(), None, Some("req_deadbeef"));
321 let Error::Auth { status, detail } = &error else {
322 panic!("expected Auth, got {error:?}");
323 };
324 assert_http_parts(
325 &error,
326 *status,
327 detail,
328 body,
329 Some("authentication_error"),
330 Some(message),
331 );
332 }
333
334 fn assert_http(status: u16, body: &str, error_type: Option<&str>, message: Option<&str>) {
335 let error = classify(status, body.as_bytes(), None, Some("req_deadbeef"));
336 let Error::Http { status, detail } = &error else {
337 panic!("expected Http, got {error:?}");
338 };
339 assert_http_parts(&error, *status, detail, body, error_type, message);
340 }
341
342 #[test]
343 fn config_error_identifies_the_invalid_setting() {
344 let error = Error::Config {
345 reason: "base URL is malformed".into(),
346 };
347
348 assert_eq!(
349 error.to_string(),
350 "the client configuration is invalid: base URL is malformed"
351 );
352 }
353
354 #[test]
355 fn classifies_400_object() {
356 assert_bad_request(
357 400,
358 fixtures::BAD_REQUEST_OBJECT,
359 Some("api_usage_error"),
360 "Invalid request.",
361 );
362 }
363
364 #[test]
365 fn classifies_400_empty_choice() {
366 assert_bad_request(
367 400,
368 fixtures::CHOICE_EMPTY,
369 None,
370 "Choice question must have at least one choice: q",
371 );
372 }
373
374 #[test]
375 fn classifies_400_too_many_choices() {
376 assert_bad_request(
377 400,
378 fixtures::CHOICE_TOO_LARGE,
379 None,
380 "Too many choices. Must have at most 255 choices.",
381 );
382 }
383
384 #[test]
385 fn classifies_400_too_many_score_levels() {
386 assert_bad_request(
387 400,
388 fixtures::SCORE_TOO_LARGE,
389 None,
390 "Too many score levels. Must have at most 10 levels.",
391 );
392 }
393
394 #[test]
395 fn classifies_400_empty_noul() {
396 assert_bad_request(
397 400,
398 fixtures::NOUL_EMPTY,
399 None,
400 "Noul question must have criteria or instructions: q",
401 );
402 }
403
404 #[test]
405 fn classifies_401_invalid_key() {
406 assert_auth(
407 401,
408 fixtures::INVALID_KEY,
409 "Cannot authenticate with the server. Please check your API key and try again.",
410 );
411 }
412
413 #[test]
414 fn classifies_403_missing_key() {
415 assert_auth(
416 403,
417 fixtures::MISSING_KEY,
418 "Must supply an API key! Check your request and try again.",
419 );
420 }
421
422 #[test]
423 fn classifies_422_empty_questions() {
424 assert_bad_request(
425 422,
426 fixtures::EMPTY_QUESTIONS,
427 None,
428 "body.questions: Dictionary should have at least 1 item after validation, not 0",
429 );
430 }
431
432 #[test]
433 fn classifies_422_empty_score_criteria() {
434 assert_bad_request(
435 422,
436 fixtures::EMPTY_SCORE,
437 None,
438 "body.questions.q.score.criteria: List should have at least 1 item after validation, not 0",
439 );
440 }
441
442 #[test]
443 fn classifies_422_missing_model() {
444 assert_bad_request(
445 422,
446 fixtures::MISSING_MODEL,
447 None,
448 "body.model: Field required",
449 );
450 }
451
452 #[test]
453 fn classifies_404_string() {
454 assert_http(404, fixtures::NOT_FOUND, None, Some("Not Found"));
455 }
456
457 #[test]
458 fn classifies_529_with_an_empty_body() {
459 let error = classify(529, b"", None, Some("req_deadbeef"));
460 let Error::Overloaded { detail } = &error else {
461 panic!("expected Overloaded, got {error:?}");
462 };
463 assert_http_parts(&error, 529, detail, "", None, None);
464 }
465
466 #[test]
467 fn classifies_429_with_retry_after() {
468 let retry_after = Duration::from_secs(2);
469 let error = classify(
470 429,
471 fixtures::CHOICE_TOO_LARGE.as_bytes(),
472 Some(retry_after),
473 Some("req_deadbeef"),
474 );
475 let Error::RateLimited {
476 retry_after: actual_retry_after,
477 detail,
478 } = &error
479 else {
480 panic!("expected RateLimited, got {error:?}");
481 };
482 assert_eq!(*actual_retry_after, Some(retry_after));
483 assert_http_parts(
484 &error,
485 429,
486 detail,
487 fixtures::CHOICE_TOO_LARGE,
488 None,
489 Some("Too many choices. Must have at most 255 choices."),
490 );
491 }
492
493 #[test]
494 fn classifies_500_with_a_non_json_body() {
495 assert_http(500, "upstream exploded", None, None);
496 }
497
498 #[test]
499 fn preserves_valid_json_with_an_unknown_shape() {
500 let body = r#"{"detail":42}"#;
501 assert_http(500, body, None, None);
502 }
503
504 #[test]
505 fn joins_multiple_pydantic_entries() {
506 let body = br#"{"detail":[{"loc":["body","questions",0],"msg":"first"},{"loc":["body","model"],"msg":"second"}]}"#;
507 let detail = ErrorDetail::parse(body, None);
508 assert_eq!(
509 detail.message.as_deref(),
510 Some("body.questions.0: first; body.model: second")
511 );
512 }
513
514 #[test]
515 fn non_utf8_body_is_preserved_lossily() {
516 let detail = ErrorDetail::parse(&[0xff], None);
517 assert_eq!(detail.raw, "�");
518 assert_eq!(detail.error_type, None);
519 assert_eq!(detail.message, None);
520 }
521}