1use serde::{Deserialize, Serialize};
4
5#[cfg(feature = "_api")]
6#[derive(Debug, thiserror::Error)]
7pub enum OpenAIError {
8 #[error("http error: {0}")]
10 Reqwest(#[from] reqwest::Error),
11 #[error("{0}")]
13 ApiError(ApiError),
14 #[error("failed to deserialize api response: error:{0} content:{1}")]
16 JSONDeserialize(serde_json::Error, String),
17 #[error("failed to save file: {0}")]
19 FileSaveError(String),
20 #[error("failed to read file: {0}")]
22 FileReadError(String),
23 #[error("stream failed: {0}")]
25 StreamError(Box<StreamError>),
26 #[error("invalid args: {0}")]
29 InvalidArgument(String),
30}
31
32#[cfg(not(feature = "_api"))]
33#[derive(Debug)]
34pub enum OpenAIError {
35 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 #[error("{0}")]
57 ReqwestEventSource(#[from] reqwest_eventsource::Error),
58 #[error("Unknown event: {0:#?}")]
60 UnknownEvent(eventsource_stream::Event),
61 #[error("EventStream error: {0}")]
63 EventStream(String),
64}
65
66#[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 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#[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}