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