speedrun_api/api/
error.rs

1use std::{error::Error};
2
3use thiserror::Error;
4
5use super::utils::ResponseError;
6
7/// Errors that occur when creating form data.
8#[derive(Debug, Error)]
9#[non_exhaustive]
10pub enum BodyError {
11    /// Error serializing body data from form paramaters
12    #[error("URL encode error: {0}")]
13    UrlEncoded(#[from] serde_urlencoded::ser::Error),
14    #[error("JSON encode error: {0}")]
15    Json(#[from] serde_json::Error),
16}
17
18/// Errors that occur from API endpoints.
19#[derive(Debug, Error)]
20#[non_exhaustive]
21pub enum ApiError<E>
22where
23    E: Error + Send + Sync + 'static,
24{
25    /// Error creating body data
26    #[error("failed to create form data: {0}")]
27    Body(#[from] BodyError),
28    /// The client encountered an error.
29    #[error("client error: {0}")]
30    Client(E),
31    /// The URL failed to parse.
32    #[error("url parse error: {0}")]
33    Parse(#[from] url::ParseError),
34    /// The endpoint requires an API key to use, but none was provided.
35    #[error("Endpoint requires authentication, but no API key was provided")]
36    RequiresAuthentication,
37    /// Error in the HTTP response
38    #[error("Error in the HTTP response at url [{url}]: source")]
39    Response {
40        /// Source of the error
41        source: ResponseError,
42        /// URL of the error
43        url: http::Uri,
44    },
45}
46
47impl<E> ApiError<E>
48where
49    E: Error + Send + Sync + 'static,
50{
51    /// Create an API error from a client error
52    pub fn client(source: E) -> Self {
53        Self::Client(source)
54    }
55
56    pub(crate) fn from_http_response(source: ResponseError, url: http::Uri) -> Self {
57        Self::Response { source, url }
58    }
59}