1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use serde::{Deserialize, Serialize};
use std::fmt;
use thiserror::Error;

/// Crate error enumeration.
#[derive(Error, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Error {
    #[error("invalid key: {0}")]
    InvalidKey(String),
    #[error("invalid user agent: {0}")]
    InvalidUserAgent(String),
    #[error("internal error: {0}")]
    Internal(String),
    #[error("request failed: {err}")]
    Request { err: String, status: Option<u16> },
    #[error("not authorized")]
    Unauthorized,
    #[error("unknown asset: {0}")]
    UnknownAsset(String),
}

impl Error {
    /// Constructs an internal error.
    pub(crate) fn internal(message: impl fmt::Display) -> Self {
        Self::Internal(message.to_string())
    }

    /// Constructs an invalid key error.
    pub(crate) fn invalid_key(message: impl fmt::Display) -> Self {
        Self::InvalidKey(message.to_string())
    }

    /// Constructs an invalid user agent error.
    pub(crate) fn invalid_agent(message: impl fmt::Display) -> Self {
        Self::InvalidUserAgent(message.to_string())
    }

    /// Constructs an unknown asset error.
    pub(crate) fn unknown_asset(message: impl fmt::Display) -> Self {
        Self::UnknownAsset(message.to_string())
    }
}

impl From<reqwest::Error> for Error {
    fn from(e: reqwest::Error) -> Self {
        Self::Request {
            err: e.to_string(),
            status: e.status().map(|c| c.as_u16()),
        }
    }
}

impl From<std::time::SystemTimeError> for Error {
    fn from(e: std::time::SystemTimeError) -> Self {
        Self::internal(e)
    }
}

impl From<hmac::crypto_mac::InvalidKeyLength> for Error {
    fn from(e: hmac::crypto_mac::InvalidKeyLength) -> Self {
        Self::invalid_key(e)
    }
}