1use core::{fmt, time::Duration};
4
5use djs_model::rest::ErrorCode;
6use http::StatusCode;
7use serde::{Deserialize, Deserializer};
8use serde_json::Value;
9
10pub(crate) type BoxError = Box<dyn std::error::Error + Send + Sync>;
12
13#[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 #[must_use]
64 pub const fn kind(&self) -> &ErrorKind {
65 &self.kind
66 }
67
68 #[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 #[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 #[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#[derive(Debug, thiserror::Error)]
103#[non_exhaustive]
104pub enum ErrorKind {
105 #[error("failed to build the request")]
108 BuildRequest,
109 #[error("failed to send the request or receive the response")]
112 Transport,
113 #[error("the request timed out")]
116 Timeout,
117 #[error("Discord responded with {status}{}", error.as_ref().map(|error| format!(": {error}")).unwrap_or_default())]
119 Response {
120 status: StatusCode,
122 error: Option<Box<ApiError>>,
124 },
125 #[error("failed to deserialize the response body")]
127 Deserialize,
128 #[error("the guild is not indexed for search yet; retry after {retry_after:?}")]
132 NotYetIndexed {
133 retry_after: Duration,
135 documents_indexed: u64,
137 },
138 #[error("refused to send: {count} invalid requests in the last 10 minutes (limit {limit})")]
143 InvalidRequestLimit {
144 count: u32,
146 limit: u32,
148 },
149}
150
151#[derive(Clone, Debug, PartialEq)]
186#[non_exhaustive]
187pub struct ApiError {
188 pub code: ErrorCode,
191 pub message: String,
193 pub field_errors: Vec<FieldError>,
197 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#[derive(Clone, Debug, PartialEq, Eq)]
239#[non_exhaustive]
240pub struct FieldError {
241 pub path: String,
244 pub code: String,
246 pub message: String,
248}
249
250impl fmt::Display for FieldError {
251 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
262fn 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#[derive(Debug, Deserialize)]
312pub(crate) struct RateLimitedBody {
313 pub(crate) retry_after: f64,
315 #[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
326pub(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
344pub(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 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 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 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}