async_openai_wasm/
error.rs1use serde::{Deserialize, Serialize};
3
4#[derive(Debug, thiserror::Error)]
5pub enum OpenAIError {
6 #[error("http error: {0}")]
8 Reqwest(#[from] reqwest::Error),
9 #[error("{0}")]
11 ApiError(ApiError),
12 #[error("failed to deserialize api response: error:{0} content:{1}")]
14 JSONDeserialize(serde_json::Error, String),
15 #[error("failed to save file: {0}")]
17 FileSaveError(String),
18 #[error("failed to read file: {0}")]
20 FileReadError(String),
21 #[error("stream failed: {0}")]
23 StreamError(StreamError),
24 #[error("invalid args: {0}")]
27 InvalidArgument(String),
28}
29
30#[derive(Debug, thiserror::Error)]
31pub enum StreamError {
32 #[error("{0}")]
34 ReqwestEventSource(#[from] reqwest_eventsource::Error),
35 #[error("Unknown event: {0:#?}")]
37 UnknownEvent(eventsource_stream::Event),
38}
39
40#[derive(Debug, Serialize, Deserialize, Clone)]
42pub struct ApiError {
43 pub message: String,
44 pub r#type: Option<String>,
45 pub param: Option<String>,
46 pub code: Option<String>,
47}
48
49impl std::fmt::Display for ApiError {
50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 let mut parts = Vec::new();
55
56 if let Some(r#type) = &self.r#type {
57 parts.push(format!("{}:", r#type));
58 }
59
60 parts.push(self.message.clone());
61
62 if let Some(param) = &self.param {
63 parts.push(format!("(param: {param})"));
64 }
65
66 if let Some(code) = &self.code {
67 parts.push(format!("(code: {code})"));
68 }
69
70 write!(f, "{}", parts.join(" "))
71 }
72}
73
74#[derive(Debug, Deserialize, Serialize)]
76pub struct WrappedError {
77 pub error: ApiError,
78}
79
80pub(crate) fn map_deserialization_error(e: serde_json::Error, bytes: &[u8]) -> OpenAIError {
81 let json_content = String::from_utf8_lossy(bytes);
82 tracing::error!("failed deserialization of: {}", json_content);
83
84 OpenAIError::JSONDeserialize(e, json_content.to_string())
85}