async_openai_wasm/
error.rs

1//! Errors originating from API calls, parsing responses, and reading-or-writing to the file system.
2use serde::{Deserialize, Serialize};
3
4#[derive(Debug, thiserror::Error)]
5pub enum OpenAIError {
6    /// Underlying error from reqwest library after an API call was made
7    #[error("http error: {0}")]
8    Reqwest(#[from] reqwest::Error),
9    /// OpenAI returns error object with details of API call failure
10    #[error("{0}")]
11    ApiError(ApiError),
12    /// Error when a response cannot be deserialized into a Rust type
13    #[error("failed to deserialize api response: error:{0} content:{1}")]
14    JSONDeserialize(serde_json::Error, String),
15    /// Error on the client side when saving file to file system
16    #[error("failed to save file: {0}")]
17    FileSaveError(String),
18    /// Error on the client side when reading file from file system
19    #[error("failed to read file: {0}")]
20    FileReadError(String),
21    /// Error on SSE streaming
22    #[error("stream failed: {0}")]
23    StreamError(StreamError),
24    /// Error from client side validation
25    /// or when builder fails to build request before making API call
26    #[error("invalid args: {0}")]
27    InvalidArgument(String),
28}
29
30#[derive(Debug, thiserror::Error)]
31pub enum StreamError {
32    /// Underlying error from reqwest_eventsource library when reading the stream
33    #[error("{0}")]
34    ReqwestEventSource(#[from] reqwest_eventsource::Error),
35    /// Error when a stream event does not match one of the expected values
36    #[error("Unknown event: {0:#?}")]
37    UnknownEvent(eventsource_stream::Event),
38}
39
40/// OpenAI API returns error object on failure
41#[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    /// If all fields are available, `ApiError` is formatted as:
51    /// `{type}: {message} (param: {param}) (code: {code})`
52    /// Otherwise, missing fields will be ignored.
53    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/// Wrapper to deserialize the error object nested in "error" JSON key
75#[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}