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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use thiserror::Error;

/// Instrument Errors.
#[derive(Debug, Error)]
pub enum InstrumentError {
    /// Instrument does not exist.
    #[error("instrument does not exist")]
    NotFound,
}

/// Exchange Errors.
#[derive(Debug, Error)]
pub enum ExchangeError {
    /// Error from layers.
    #[error("layer: {0}")]
    Layer(#[from] Box<dyn std::error::Error + Send + Sync>),
    #[cfg(feature = "http")]
    /// Http errors.
    #[error("http: {0}")]
    Http(hyper::Error),
    /// All other errors.
    #[error(transparent)]
    Other(#[from] anyhow::Error),
    /// All other api errors.
    #[error("api: {0}")]
    Api(anyhow::Error),
    /// Unavailable.
    #[error("unavailable: {0}")]
    Unavailable(anyhow::Error),
    /// Instrument errors.
    #[error("instrument: {0}")]
    Instrument(InstrumentError),
    /// Rate limited.
    #[error("rate limited: {0}")]
    RateLimited(anyhow::Error),
    /// API Key error.
    #[error("key error: {0}")]
    KeyError(anyhow::Error),
    /// Order not found.
    #[error("order not found")]
    OrderNotFound,
    /// Forbidden.
    #[error("forbidden: {0}")]
    Forbidden(anyhow::Error),
}

impl ExchangeError {
    /// Is temporary.
    pub fn is_temporary(&self) -> bool {
        #[cfg(feature = "http")]
        {
            matches!(
                self,
                Self::RateLimited(_) | Self::Unavailable(_) | Self::Http(_)
            )
        }
        #[cfg(not(feature = "http"))]
        {
            matches!(self, Self::RateLimited(_) | Self::Unavailable(_))
        }
    }

    /// Flatten.
    pub fn flatten(self) -> Self {
        match self {
            Self::Layer(err) => match err.downcast::<Self>() {
                Ok(err) => (*err).flatten(),
                Err(err) => Self::Other(anyhow::anyhow!("{err}")),
            },
            err => err,
        }
    }

    /// Flatten layered error.
    pub fn layer(err: Box<dyn std::error::Error + Send + Sync>) -> Self {
        match err.downcast::<Self>() {
            Ok(err) => (*err).flatten(),
            Err(err) => Self::Other(anyhow::anyhow!("{err}")),
        }
    }
}