async_openai/
error.rs

1//! Errors originating from API calls, parsing responses, and reading-or-writing to the file system.
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, thiserror::Error)]
6pub enum OpenAIError {
7    /// Underlying error from reqwest library after an API call was made
8    #[error("http error: {0}")]
9    Reqwest(#[from] reqwest::Error),
10    /// OpenAI returns error object with details of API call failure
11    #[error("{0}")]
12    ApiError(ApiError),
13    /// Error when a response cannot be deserialized into a Rust type
14    #[error("failed to deserialize api response: error:{0} content:{1}")]
15    JSONDeserialize(serde_json::Error, String),
16    /// Error on the client side when saving file to file system
17    #[error("failed to save file: {0}")]
18    FileSaveError(String),
19    /// Error on the client side when reading file from file system
20    #[error("failed to read file: {0}")]
21    FileReadError(String),
22    /// Error on SSE streaming
23    #[error("stream failed: {0}")]
24    StreamError(Box<StreamError>),
25    /// Error from client side validation
26    /// or when builder fails to build request before making API call
27    #[error("invalid args: {0}")]
28    InvalidArgument(String),
29}
30
31#[derive(Debug, thiserror::Error)]
32pub enum StreamError {
33    /// Underlying error from reqwest_eventsource library when reading the stream
34    #[error("{0}")]
35    ReqwestEventSource(#[from] reqwest_eventsource::Error),
36    /// Error when a stream event does not match one of the expected values
37    #[error("Unknown event: {0:#?}")]
38    UnknownEvent(eventsource_stream::Event),
39    /// Error from eventsource_stream when parsing SSE
40    #[error("EventStream error: {0}")]
41    EventStream(String),
42}
43
44/// OpenAI API returns error object on failure
45#[derive(Debug, Serialize, Deserialize, Clone)]
46pub struct ApiError {
47    pub message: String,
48    pub r#type: Option<String>,
49    pub param: Option<String>,
50    pub code: Option<String>,
51}
52
53impl std::fmt::Display for ApiError {
54    /// If all fields are available, `ApiError` is formatted as:
55    /// `{type}: {message} (param: {param}) (code: {code})`
56    /// Otherwise, missing fields will be ignored.
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        let mut parts = Vec::new();
59
60        if let Some(r#type) = &self.r#type {
61            parts.push(format!("{}:", r#type));
62        }
63
64        parts.push(self.message.clone());
65
66        if let Some(param) = &self.param {
67            parts.push(format!("(param: {param})"));
68        }
69
70        if let Some(code) = &self.code {
71            parts.push(format!("(code: {code})"));
72        }
73
74        write!(f, "{}", parts.join(" "))
75    }
76}
77
78/// Wrapper to deserialize the error object nested in "error" JSON key
79#[derive(Debug, Deserialize, Serialize)]
80pub struct WrappedError {
81    pub error: ApiError,
82}
83
84pub(crate) fn map_deserialization_error(e: serde_json::Error, bytes: &[u8]) -> OpenAIError {
85    let json_content = String::from_utf8_lossy(bytes);
86    tracing::error!("failed deserialization of: {}", json_content);
87
88    OpenAIError::JSONDeserialize(e, json_content.to_string())
89}