Skip to main content

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
5pub use crate::types::shared::{
6    MisalignmentErrorDetailsResource, MisalignmentErrorType, MisalignmentSteer,
7};
8
9#[cfg(feature = "_api")]
10#[derive(Debug, thiserror::Error)]
11pub enum OpenAIError {
12    /// Underlying error from reqwest library after an API call was made
13    #[error("http error: {0}")]
14    Reqwest(#[from] reqwest::Error),
15    /// OpenAI returns error object with details of API call failure, along
16    /// with the HTTP status code from the response.
17    #[error("{0}")]
18    ApiError(ApiErrorResponse),
19    /// Error when a response cannot be deserialized into a Rust type
20    #[error("failed to deserialize api response: error:{0} content:{1}")]
21    JSONDeserialize(serde_json::Error, String),
22    #[cfg(all(feature = "_api", not(target_family = "wasm")))]
23    /// Error on the client side when saving file to file system
24    #[error("failed to save file: {0}")]
25    FileSaveError(String),
26    #[cfg(all(feature = "_api", not(target_family = "wasm")))]
27    /// Error on the client side when reading file from file system
28    #[error("failed to read file: {0}")]
29    FileReadError(String),
30    /// Error on SSE streaming
31    #[error("stream failed: {0}")]
32    StreamError(Box<StreamError>),
33    /// Error from middlewares
34    #[cfg(feature = "middleware")]
35    #[error(transparent)]
36    Boxed(Box<dyn std::error::Error + Send + Sync + 'static>),
37    /// Error from client side validation
38    /// or when builder fails to build request before making API call
39    #[error("invalid args: {0}")]
40    InvalidArgument(String),
41}
42
43#[cfg(all(feature = "_api", feature = "middleware"))]
44impl From<tower::BoxError> for OpenAIError {
45    fn from(error: tower::BoxError) -> Self {
46        OpenAIError::Boxed(error)
47    }
48}
49
50#[cfg(not(feature = "_api"))]
51#[derive(Debug)]
52pub enum OpenAIError {
53    /// Error from client side validation
54    /// or when builder fails to build request before making API call
55    InvalidArgument(String),
56}
57
58#[cfg(not(feature = "_api"))]
59impl std::fmt::Display for OpenAIError {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        match self {
62            OpenAIError::InvalidArgument(msg) => write!(f, "invalid args: {}", msg),
63        }
64    }
65}
66
67#[cfg(not(feature = "_api"))]
68impl std::error::Error for OpenAIError {}
69
70#[cfg(feature = "_api")]
71#[derive(Debug, thiserror::Error)]
72pub enum StreamError {
73    /// Error when a stream event does not match one of the expected values
74    #[error("Unknown event: {0:#?}")]
75    UnknownEvent(eventsource_stream::Event),
76    /// Error from eventsource_stream when parsing SSE
77    #[error("EventStream error: {0}")]
78    EventStream(String),
79}
80
81/// OpenAI API returns error object on failure
82#[derive(Debug, Serialize, Deserialize, Clone)]
83pub struct ApiError {
84    pub message: String,
85    pub r#type: Option<String>,
86    pub param: Option<String>,
87    pub code: Option<String>,
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub misalignment: Option<Box<MisalignmentErrorDetailsResource>>,
90}
91
92impl std::fmt::Display for ApiError {
93    /// If all fields are available, `ApiError` is formatted as:
94    /// `{type}: {message} (param: {param}) (code: {code})`
95    /// Otherwise, missing fields will be ignored.
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        let mut parts = Vec::new();
98
99        if let Some(r#type) = &self.r#type {
100            parts.push(format!("{}:", r#type));
101        }
102
103        parts.push(self.message.clone());
104
105        if let Some(param) = &self.param {
106            parts.push(format!("(param: {param})"));
107        }
108
109        if let Some(code) = &self.code {
110            parts.push(format!("(code: {code})"));
111        }
112
113        write!(f, "{}", parts.join(" "))
114    }
115}
116
117impl std::error::Error for ApiError {}
118
119/// `ApiError` paired with the HTTP status code from the response.
120#[cfg(feature = "_api")]
121#[derive(Debug, Clone)]
122pub struct ApiErrorResponse {
123    /// HTTP status code
124    pub status_code: reqwest::StatusCode,
125    /// Parsed error from response
126    pub api_error: ApiError,
127}
128
129#[cfg(feature = "_api")]
130impl std::fmt::Display for ApiErrorResponse {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        write!(f, "{} {}", self.status_code, self.api_error)
133    }
134}
135
136#[cfg(feature = "_api")]
137impl std::error::Error for ApiErrorResponse {}
138
139/// Wrapper to deserialize the error object nested in "error" JSON key
140#[derive(Debug, Deserialize, Serialize)]
141pub struct WrappedError {
142    pub error: ApiError,
143}
144
145#[cfg(feature = "_api")]
146pub(crate) fn map_deserialization_error(e: serde_json::Error, bytes: &[u8]) -> OpenAIError {
147    let json_content = String::from_utf8_lossy(bytes);
148    tracing::error!("failed deserialization of: {}", json_content);
149
150    OpenAIError::JSONDeserialize(e, json_content.to_string())
151}