Skip to main content

openai_oxide/
error.rs

1// OpenAI API error types
2
3use serde::{Deserialize, Serialize};
4
5/// Serialize a `#[serde(rename_all = "...")]` string enum to its JSON name.
6///
7/// Used in multipart form fields where we need the renamed string (e.g. `"fine-tune"`)
8/// instead of the Rust variant name.
9pub(crate) fn enum_to_string<T: Serialize>(value: &T) -> Result<String, OpenAIError> {
10    let v = serde_json::to_value(value)?;
11    v.as_str()
12        .map(|s| s.to_string())
13        .ok_or_else(|| OpenAIError::InvalidArgument(format!("expected string enum, got {v}")))
14}
15
16/// Error response body from the OpenAI API.
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct ErrorResponse {
19    pub error: ApiErrorDetail,
20}
21
22/// Detail within an API error response.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct ApiErrorDetail {
25    pub message: String,
26    #[serde(rename = "type")]
27    pub type_: Option<String>,
28    pub param: Option<String>,
29    pub code: Option<String>,
30}
31
32/// All errors that can occur when using this library.
33#[derive(Debug, thiserror::Error)]
34pub enum OpenAIError {
35    /// The API returned an error response.
36    #[error("API error (status {status}): {message}")]
37    ApiError {
38        status: u16,
39        message: String,
40        type_: Option<String>,
41        code: Option<String>,
42        /// The `x-request-id` header value for debugging with OpenAI support.
43        request_id: Option<String>,
44    },
45
46    /// HTTP request failed.
47    #[error("request error: {0}")]
48    RequestError(#[from] reqwest::Error),
49
50    /// JSON (de)serialization failed.
51    #[error("JSON error: {0}")]
52    JsonError(#[from] serde_json::Error),
53
54    /// SSE stream error.
55    #[error("stream error: {0}")]
56    StreamError(String),
57
58    /// Invalid argument passed by the caller.
59    #[error("invalid argument: {0}")]
60    InvalidArgument(String),
61
62    /// WebSocket error.
63    #[cfg(feature = "websocket")]
64    #[error("websocket error: {0}")]
65    WebSocketError(String),
66}