llm_rs/
api_error.rs

1use reqwest::StatusCode;
2use std::collections::HashMap;
3use std::{error::Error, fmt};
4
5#[derive(Debug)]
6pub enum ApiErrorType {
7    BadJson(String),
8    FailedRequest(String),
9    Error(String),
10    // When a bad status is returned from a network connection.
11    // Includes the failing code and the textual error string
12    Status(StatusCode, String),
13}
14
15#[derive(Debug)]
16pub struct ApiError {
17    pub error_type: ApiErrorType,
18    pub headers: HashMap<String, String>,
19}
20impl ApiError {
21    pub fn new(error_type: ApiErrorType, headers: HashMap<String, String>) -> Self {
22        Self {
23            error_type,
24            headers,
25        }
26    }
27}
28impl fmt::Display for ApiError {
29    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
30        let header_report: String = self
31            .headers
32            .iter()
33            .fold(String::new(), |a, (b0, b1)| format!("{a}\n{b0}:{b1}"));
34        match self.error_type {
35            ApiErrorType::FailedRequest(ref msg) => {
36                write!(f, "{header_report}\nFailed Request: {msg}")
37            }
38            ApiErrorType::BadJson(ref msg) => write!(f, "Bad JSON: {}", msg),
39
40            // HTTP failure.  Not a 200 status
41            ApiErrorType::Status(ref status, ref reason) => {
42                write!(f, "{header_report}\nHTTP Status({status}) Reason: {reason}")
43            }
44
45            // Generic.  TODO: Get rid of this
46            ApiErrorType::Error(ref msg) => write!(f, "{header_report}\nError: {msg}"),
47        }
48    }
49}
50
51impl Error for ApiError {
52    fn source(&self) -> Option<&(dyn Error + 'static)> {
53        None
54    }
55}