Skip to main content

minimax_client/
error.rs

1//! Error types returned by this crate.
2
3use thiserror::Error;
4
5/// Errors returned by the MiniMax API client.
6///
7/// This enum is `#[non_exhaustive]`: new variants may be added in future
8/// releases, so downstream `match` expressions need a `_` arm.
9#[derive(Debug, Error)]
10#[non_exhaustive]
11pub enum Error {
12    /// The HTTP request could not be completed (connection failure, timeout,
13    /// TLS error, and so on).
14    #[error("HTTP request failed: {0}")]
15    Http(#[from] reqwest::Error),
16
17    /// MiniMax accepted the request but reported an error in `base_resp`.
18    ///
19    /// Common codes are `1002` (rate limited), `1004` (authentication failed),
20    /// `1008` (insufficient balance) and `2013` (invalid parameters).
21    #[error("MiniMax API error {code}: {msg}")]
22    ApiError {
23        /// The `base_resp.status_code` value reported by MiniMax.
24        code: i64,
25        /// The `base_resp.status_msg` value reported by MiniMax.
26        msg: String,
27    },
28
29    /// The response body could not be parsed as the expected JSON shape.
30    #[error("JSON parse error: {0}")]
31    Json(#[from] serde_json::Error),
32
33    /// A hex-encoded audio payload could not be decoded.
34    #[error("hex decode error: {0}")]
35    Hex(#[from] hex::FromHexError),
36
37    /// A streaming endpoint replied without a `text/event-stream` body.
38    #[error("server returned a non-SSE response (HTTP {status})")]
39    NotSse {
40        /// The HTTP status of the offending response.
41        status: reqwest::StatusCode,
42    },
43
44    /// The server returned a non-success HTTP status and no usable
45    /// `base_resp` error to report.
46    #[error("unexpected HTTP status {status}: {body}")]
47    UnexpectedStatus {
48        /// The HTTP status returned by the server.
49        status: reqwest::StatusCode,
50        /// The response body, truncated to a reasonable length.
51        body: String,
52    },
53
54    /// The request succeeded but carried no audio payload.
55    #[error("audio data is empty")]
56    EmptyAudio,
57
58    /// A required field was absent from an otherwise successful response.
59    #[error("missing field `{0}` in response")]
60    MissingField(&'static str),
61
62    /// Any other error that does not fit the variants above.
63    #[error("{0}")]
64    Other(String),
65}
66
67impl Error {
68    /// The MiniMax `base_resp.status_code`, if this is an [`Error::ApiError`].
69    pub fn api_code(&self) -> Option<i64> {
70        match self {
71            Error::ApiError { code, .. } => Some(*code),
72            _ => None,
73        }
74    }
75
76    /// The HTTP status carried by this error, when there is one.
77    pub fn status(&self) -> Option<reqwest::StatusCode> {
78        match self {
79            Error::NotSse { status } | Error::UnexpectedStatus { status, .. } => Some(*status),
80            Error::Http(e) => e.status(),
81            _ => None,
82        }
83    }
84
85    /// Whether the request failed because the API key was rejected.
86    pub fn is_auth_error(&self) -> bool {
87        self.api_code() == Some(1004)
88            || self.status() == Some(reqwest::StatusCode::UNAUTHORIZED)
89            || self.status() == Some(reqwest::StatusCode::FORBIDDEN)
90    }
91
92    /// Whether the request was rejected for exceeding a rate limit.
93    pub fn is_rate_limited(&self) -> bool {
94        self.api_code() == Some(1002)
95            || self.status() == Some(reqwest::StatusCode::TOO_MANY_REQUESTS)
96    }
97
98    /// Whether retrying the same request has a reasonable chance of success.
99    ///
100    /// Covers transport-level timeouts and connection failures, rate limits,
101    /// and server-side errors. It is still up to the caller to apply a backoff.
102    pub fn is_retryable(&self) -> bool {
103        if self.is_rate_limited() {
104            return true;
105        }
106        if let Error::Http(e) = self {
107            if e.is_timeout() || e.is_connect() {
108                return true;
109            }
110        }
111        match self.api_code() {
112            // 1000 unknown error, 1001 request timeout, 1013 internal error.
113            Some(1000 | 1001 | 1013) => true,
114            _ => self.status().is_some_and(|s| s.is_server_error()),
115        }
116    }
117}
118
119/// A specialized [`Result`](std::result::Result) alias for this crate.
120pub type Result<T> = std::result::Result<T, Error>;