Skip to main content

djs_rest/
error.rs

1//! Errors returned by the REST client.
2
3use core::{fmt, time::Duration};
4
5use djs_model::rest::ErrorCode;
6use http::StatusCode;
7use serde::{Deserialize, Deserializer};
8use serde_json::Value;
9
10/// A boxed error source.
11pub(crate) type BoxError = Box<dyn std::error::Error + Send + Sync>;
12
13/// An error returned by [`Rest`](crate::Rest).
14///
15/// The error is deliberately small (a kind plus an optional boxed source) so `Result<T, Error>`
16/// stays cheap to move around. Inspect it with [`kind`](Self::kind), or use the shortcuts
17/// [`status`](Self::status) and [`api_error`](Self::api_error).
18///
19/// discord.js counterpart: `DiscordAPIError`, `HTTPError` and `RateLimitError` (`@discordjs/rest`).
20///
21/// # Examples
22///
23/// ```no_run
24/// # async fn example(rest: djs_rest::Rest, channel_id: djs_model::id::ChannelId) {
25/// use djs_model::rest::ErrorCode;
26///
27/// match rest.create_message(channel_id, &"hi".into()).await {
28///     Ok(message) => println!("sent {}", message.id),
29///     Err(error)
30///         if error
31///             .api_error()
32///             .is_some_and(|api| api.code == ErrorCode::MissingPermissions) =>
33///     {
34///         eprintln!("missing permissions");
35///     }
36///     Err(error) => eprintln!("request failed: {error}"),
37/// }
38/// # }
39/// ```
40#[derive(Debug, thiserror::Error)]
41#[error("{kind}")]
42pub struct Error {
43    kind: ErrorKind,
44    #[source]
45    source: Option<BoxError>,
46}
47
48impl Error {
49    pub(crate) fn new(kind: ErrorKind) -> Self {
50        Self { kind, source: None }
51    }
52
53    pub(crate) fn with_source(kind: ErrorKind, source: impl Into<BoxError>) -> Self {
54        Self {
55            kind,
56            source: Some(source.into()),
57        }
58    }
59
60    /// Returns what went wrong.
61    ///
62    /// discord.js counterpart: the class of the error `@discordjs/rest` rejects with (`DiscordAPIError`, `HTTPError`, `RateLimitError`).
63    #[must_use]
64    pub const fn kind(&self) -> &ErrorKind {
65        &self.kind
66    }
67
68    /// Consumes the error, returning its kind and underlying source.
69    ///
70    /// discord.js counterpart: none (JavaScript errors are not taken apart).
71    #[must_use]
72    pub fn into_parts(self) -> (ErrorKind, Option<Box<dyn std::error::Error + Send + Sync>>) {
73        (self.kind, self.source)
74    }
75
76    /// Returns the HTTP status code, if Discord responded with an error status.
77    ///
78    /// discord.js counterpart: `DiscordAPIError#status` (`@discordjs/rest`).
79    #[must_use]
80    pub fn status(&self) -> Option<StatusCode> {
81        match &self.kind {
82            ErrorKind::Response { status, .. } => Some(*status),
83            _ => None,
84        }
85    }
86
87    /// Returns the error body Discord sent, if any.
88    ///
89    /// discord.js counterpart: `DiscordAPIError#rawError` (`@discordjs/rest`).
90    #[must_use]
91    pub fn api_error(&self) -> Option<&ApiError> {
92        match &self.kind {
93            ErrorKind::Response { error, .. } => error.as_deref(),
94            _ => None,
95        }
96    }
97}
98
99/// The kind of an [`Error`].
100///
101/// discord.js counterpart: `DiscordAPIError`, `HTTPError` and `RateLimitError` (`@discordjs/rest`).
102#[derive(Debug, thiserror::Error)]
103#[non_exhaustive]
104pub enum ErrorKind {
105    /// The request could not be built — for example the token contains characters that are not
106    /// allowed in an HTTP header, or the body could not be serialized.
107    #[error("failed to build the request")]
108    BuildRequest,
109    /// The request could not be sent or the response could not be received (DNS, TCP, TLS,
110    /// HTTP protocol errors). Retried automatically up to the configured number of times.
111    #[error("failed to send the request or receive the response")]
112    Transport,
113    /// No complete response arrived within the configured timeout. Retried automatically up to
114    /// the configured number of times.
115    #[error("the request timed out")]
116    Timeout,
117    /// Discord responded with a non-success status code.
118    #[error("Discord responded with {status}{}", error.as_ref().map(|error| format!(": {error}")).unwrap_or_default())]
119    Response {
120        /// The HTTP status code.
121        status: StatusCode,
122        /// The parsed error body, if the response contained one.
123        error: Option<Box<ApiError>>,
124    },
125    /// The response body could not be deserialized into the expected type.
126    #[error("failed to deserialize the response body")]
127    Deserialize,
128    /// [Search Guild Messages](crate::Rest::search_guild_messages) found the guild not indexed
129    /// yet (Discord answered `202 Accepted`, D-104). Retry after `retry_after`; Discord sends
130    /// zero when it wants "a short delay".
131    #[error("the guild is not indexed for search yet; retry after {retry_after:?}")]
132    NotYetIndexed {
133        /// How long to wait before retrying.
134        retry_after: Duration,
135        /// How many documents the running indexing has processed so far.
136        documents_indexed: u64,
137    },
138    /// The request was not sent because the client already made as many invalid requests (401,
139    /// 403, 429) in the last 10 minutes as the configured
140    /// [`invalid_request_limit`](crate::RestBuilder::invalid_request_limit) allows (D-085).
141    /// Discord temporarily bans the IP at 10 000.
142    #[error("refused to send: {count} invalid requests in the last 10 minutes (limit {limit})")]
143    InvalidRequestLimit {
144        /// The invalid requests counted in the window.
145        count: u32,
146        /// The configured limit.
147        limit: u32,
148    },
149}
150
151/// The JSON error body Discord returns with 4xx responses.
152///
153/// Its [`Display`](fmt::Display) shows the message and code, then one line per
154/// [field error](Self::field_errors), e.g.:
155///
156/// ```text
157/// Invalid Form Body (code 50035)
158/// embeds[0].title[BASE_TYPE_REQUIRED]: This field is required
159/// ```
160///
161/// See [error messages](https://docs.discord.com/developers/reference#error-messages) and
162/// [JSON error codes](https://docs.discord.com/developers/topics/opcodes-and-status-codes#json).
163///
164/// discord.js counterpart: `DiscordAPIError`.
165///
166/// # Examples
167///
168/// ```
169/// use djs_model::rest::ErrorCode;
170/// use djs_rest::ApiError;
171///
172/// let error: ApiError = serde_json::from_str(
173///     r#"{"code": 50035, "message": "Invalid Form Body", "errors": {
174///         "content": {"_errors": [{"code": "BASE_TYPE_MAX_LENGTH",
175///                                  "message": "Must be 2000 or fewer in length."}]}}}"#,
176/// )
177/// .unwrap();
178/// assert_eq!(error.code, ErrorCode::InvalidFormBodyOrContentType);
179/// assert_eq!(error.field_errors[0].path, "content");
180/// assert_eq!(
181///     error.to_string(),
182///     "Invalid Form Body (code 50035)\ncontent[BASE_TYPE_MAX_LENGTH]: Must be 2000 or fewer in length."
183/// );
184/// ```
185#[derive(Clone, Debug, PartialEq)]
186#[non_exhaustive]
187pub struct ApiError {
188    /// The [JSON error code](https://docs.discord.com/developers/topics/opcodes-and-status-codes#json-json-error-codes),
189    /// e.g. [`MissingPermissions`](ErrorCode::MissingPermissions) (D-097).
190    pub code: ErrorCode,
191    /// A human-readable description of the error.
192    pub message: String,
193    /// The detailed errors of the request's fields (mostly with
194    /// [`InvalidFormBodyOrContentType`](ErrorCode::InvalidFormBodyOrContentType)), flattened
195    /// from [`errors`](Self::errors) (D-099). Empty if Discord sent none.
196    pub field_errors: Vec<FieldError>,
197    /// The nested `errors` object as Discord sent it.
198    pub errors: Option<Value>,
199}
200
201impl<'de> Deserialize<'de> for ApiError {
202    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
203        #[derive(Deserialize)]
204        struct Raw {
205            code: ErrorCode,
206            message: String,
207            #[serde(default)]
208            errors: Option<Value>,
209        }
210
211        let raw = Raw::deserialize(deserializer)?;
212        let mut field_errors = Vec::new();
213        if let Some(errors) = &raw.errors {
214            flatten_errors(errors, &mut String::new(), &mut field_errors);
215        }
216        Ok(Self {
217            code: raw.code,
218            message: raw.message,
219            field_errors,
220            errors: raw.errors,
221        })
222    }
223}
224
225impl fmt::Display for ApiError {
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        write!(f, "{} (code {})", self.message, self.code.value())?;
228        for error in &self.field_errors {
229            write!(f, "\n{error}")?;
230        }
231        Ok(())
232    }
233}
234
235/// An error of one field of a request body, from the `errors` of an [`ApiError`] (D-099).
236///
237/// discord.js counterpart: the lines of a `DiscordAPIError` message after the first.
238#[derive(Clone, Debug, PartialEq, Eq)]
239#[non_exhaustive]
240pub struct FieldError {
241    /// Where the field is in the request body, e.g. `embeds[0].title`; empty for an error of
242    /// the request as a whole.
243    pub path: String,
244    /// What is wrong, e.g. `BASE_TYPE_REQUIRED` (empty if Discord sent only a message).
245    pub code: String,
246    /// A human-readable description.
247    pub message: String,
248}
249
250impl fmt::Display for FieldError {
251    /// `path[CODE]: message`, leaving out the parts that are empty.
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        match (self.path.is_empty(), self.code.is_empty()) {
254            (false, false) => write!(f, "{}[{}]: {}", self.path, self.code, self.message),
255            (false, true) => write!(f, "{}: {}", self.path, self.message),
256            (true, false) => write!(f, "{}: {}", self.code, self.message),
257            (true, true) => f.write_str(&self.message),
258        }
259    }
260}
261
262/// Collects the errors of a nested `errors` value. Object keys extend the path (`.name`, or
263/// `[n]` for array indices), except keys starting with `_` such as `_errors`, the lists of
264/// `{code, message}` errors of a field. Depth is bounded by `serde_json`'s recursion limit.
265fn flatten_errors(value: &Value, path: &mut String, out: &mut Vec<FieldError>) {
266    match value {
267        Value::Object(object) => {
268            if let (Some(Value::String(code)), Some(Value::String(message))) =
269                (object.get("code"), object.get("message"))
270            {
271                out.push(FieldError {
272                    path: path.clone(),
273                    code: code.clone(),
274                    message: message.clone(),
275                });
276                return;
277            }
278            for (key, child) in object {
279                let length = path.len();
280                if !key.starts_with('_') {
281                    if path.is_empty() {
282                        path.push_str(key);
283                    } else if key.bytes().all(|byte| byte.is_ascii_digit()) {
284                        path.push('[');
285                        path.push_str(key);
286                        path.push(']');
287                    } else {
288                        path.push('.');
289                        path.push_str(key);
290                    }
291                }
292                flatten_errors(child, path, out);
293                path.truncate(length);
294            }
295        }
296        Value::Array(items) => {
297            for item in items {
298                flatten_errors(item, path, out);
299            }
300        }
301        Value::String(message) => out.push(FieldError {
302            path: path.clone(),
303            code: String::new(),
304            message: message.clone(),
305        }),
306        _ => {}
307    }
308}
309
310/// The body of a 429 response.
311#[derive(Debug, Deserialize)]
312pub(crate) struct RateLimitedBody {
313    /// Seconds to wait before retrying.
314    pub(crate) retry_after: f64,
315    /// Whether the global rate limit was hit.
316    #[serde(default)]
317    pub(crate) global: bool,
318}
319
320impl RateLimitedBody {
321    pub(crate) fn retry_after(&self) -> Duration {
322        seconds(self.retry_after)
323    }
324}
325
326/// The error for a `202 Accepted` answer of Search Guild Messages (D-104), whose body looks
327/// like `{"message": …, "code": 110000, "documents_indexed": 0, "retry_after": 2}`.
328pub(crate) fn not_yet_indexed(body: &[u8]) -> Error {
329    #[derive(Deserialize, Default)]
330    struct NotIndexed {
331        #[serde(default)]
332        retry_after: f64,
333        #[serde(default)]
334        documents_indexed: u64,
335    }
336
337    let body: NotIndexed = serde_json::from_slice(body).unwrap_or_default();
338    Error::new(ErrorKind::NotYetIndexed {
339        retry_after: seconds(body.retry_after),
340        documents_indexed: body.documents_indexed,
341    })
342}
343
344/// Converts a (possibly malformed) number of seconds into a `Duration`, clamping invalid values
345/// to zero and absurdly large ones to one hour.
346pub(crate) fn seconds(value: f64) -> Duration {
347    if value.is_finite() && value > 0.0 {
348        Duration::from_secs_f64(value.min(3_600.0))
349    } else {
350        Duration::ZERO
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn display() {
360        let error = Error::new(ErrorKind::Response {
361            status: StatusCode::FORBIDDEN,
362            error: Some(Box::new(ApiError {
363                code: ErrorCode::MissingPermissions,
364                message: "Missing Permissions".into(),
365                field_errors: Vec::new(),
366                errors: None,
367            })),
368        });
369        assert_eq!(
370            error.to_string(),
371            "Discord responded with 403 Forbidden: Missing Permissions (code 50013)"
372        );
373        assert_eq!(error.status(), Some(StatusCode::FORBIDDEN));
374        assert_eq!(
375            error.api_error().unwrap().code,
376            ErrorCode::MissingPermissions
377        );
378    }
379
380    fn parse(json: &str) -> ApiError {
381        serde_json::from_str(json).unwrap()
382    }
383
384    fn lines(error: &ApiError) -> Vec<String> {
385        error.field_errors.iter().map(ToString::to_string).collect()
386    }
387
388    #[test]
389    fn field_errors_of_the_docs_examples() {
390        // The docs' "Array Error", "Object Error" and "Request Error" examples.
391        let array = parse(
392            r#"{"code": 50035, "errors": {"activities": {"0": {
393                "platform": {"_errors": [{"code": "BASE_TYPE_CHOICES",
394                    "message": "Value must be one of ('desktop', 'android', 'ios')."}]},
395                "type": {"_errors": [{"code": "BASE_TYPE_CHOICES",
396                    "message": "Value must be one of (0, 1, 2, 3, 4, 5)."}]}}}},
397                "message": "Invalid Form Body"}"#,
398        );
399        assert_eq!(array.code, ErrorCode::InvalidFormBodyOrContentType);
400        assert_eq!(
401            lines(&array),
402            [
403                "activities[0].platform[BASE_TYPE_CHOICES]: Value must be one of ('desktop', 'android', 'ios').",
404                "activities[0].type[BASE_TYPE_CHOICES]: Value must be one of (0, 1, 2, 3, 4, 5).",
405            ]
406        );
407        assert!(array.errors.is_some());
408
409        let object = parse(
410            r#"{"code": 50035, "errors": {"access_token": {"_errors": [
411                {"code": "BASE_TYPE_REQUIRED", "message": "This field is required"}]}},
412                "message": "Invalid Form Body"}"#,
413        );
414        assert_eq!(
415            object.to_string(),
416            "Invalid Form Body (code 50035)\naccess_token[BASE_TYPE_REQUIRED]: This field is required"
417        );
418
419        let request = parse(
420            r#"{"code": 50035, "message": "Invalid Form Body", "errors": {"_errors": [
421                {"code": "APPLICATION_COMMAND_TOO_LARGE",
422                 "message": "Command exceeds maximum size (8000)"}]}}"#,
423        );
424        assert_eq!(request.field_errors[0].path, "");
425        assert_eq!(
426            lines(&request),
427            ["APPLICATION_COMMAND_TOO_LARGE: Command exceeds maximum size (8000)"]
428        );
429    }
430
431    #[test]
432    fn unusual_error_shapes() {
433        // Top-level indices (bulk command overwrites), a field named `code`, a plain string,
434        // and an unknown error code.
435        let error = parse(
436            r#"{"code": 123456, "message": "Something", "errors": {
437                "0": {"code": {"_errors": [{"code": "NUMBER_TYPE_MAX", "message": "Too big"}]}},
438                "name": "Must be set",
439                "other": 5}}"#,
440        );
441        assert_eq!(error.code, ErrorCode::Unknown(123_456));
442        assert_eq!(
443            lines(&error),
444            ["0.code[NUMBER_TYPE_MAX]: Too big", "name: Must be set"]
445        );
446        let plain = parse(r#"{"code": 0, "message": "404: Not Found"}"#);
447        assert_eq!(plain.code, ErrorCode::GeneralError);
448        assert!(plain.field_errors.is_empty() && plain.errors.is_none());
449        assert_eq!(plain.to_string(), "404: Not Found (code 0)");
450    }
451
452    #[test]
453    fn size() {
454        // Kind + optional boxed source; keep `Result<T, Error>` small.
455        assert!(size_of::<Error>() <= 48, "{}", size_of::<Error>());
456    }
457
458    #[test]
459    fn seconds_is_robust() {
460        assert_eq!(seconds(f64::NAN), Duration::ZERO);
461        assert_eq!(seconds(-1.0), Duration::ZERO);
462        assert_eq!(seconds(0.25), Duration::from_millis(250));
463        assert_eq!(seconds(1e12), Duration::from_secs(3_600));
464    }
465}