Skip to main content

ccxt_base/
error.rs

1// Native Rust – hand-written error types for CCXT.
2//
3// The hierarchy mirrors errorHierarchy.js. ExchangeError wraps all runtime
4// failures with a `kind` string so that exchange code and the generated
5// exchange_errors.rs can construct typed errors without a huge enum.
6
7use thiserror::Error;
8
9/// A runtime exchange error. `kind` is the class name from the TS hierarchy
10/// (e.g. "AuthenticationError", "InsufficientFunds"). `message` is the
11/// human-readable description.
12#[derive(Debug, Clone, Error)]
13#[error("[{kind}] {message}")]
14pub struct ExchangeError {
15    /// Error class name, e.g. "NetworkError", "AuthenticationError"
16    pub kind: String,
17    /// Human-readable message
18    pub message: String,
19}
20
21impl ExchangeError {
22    /// Create a new error with the given kind and message.
23    pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
24        Self { kind: kind.into(), message: message.into() }
25    }
26
27    /// Returns `true` when this is the named error class *or* a sub-class of it,
28    /// walking the CCXT error hierarchy (errorHierarchy.ts). E.g. a `BadSymbol`
29    /// `is("BadRequest")` and a `RequestTimeout` `is("NetworkError")`.
30    pub fn is(&self, kind: &str) -> bool {
31        let mut current = self.kind.as_str();
32        loop {
33            if current == kind {
34                return true;
35            }
36            match error_parent(current) {
37                Some(p) => current = p,
38                None => return false,
39            }
40        }
41    }
42
43    /// Alias for `is` — clearer at call sites asserting subclass membership.
44    pub fn is_a(&self, kind: &str) -> bool {
45        self.is(kind)
46    }
47}
48
49/// Parent class of a CCXT error kind per `ts/src/base/errorHierarchy.ts`.
50/// `None` for the root (`BaseError`) or an unknown kind.
51fn error_parent(kind: &str) -> Option<&'static str> {
52    Some(match kind {
53        // BaseError → ExchangeError subtree
54        "ExchangeError"            => "BaseError",
55        "AuthenticationError"      => "ExchangeError",
56        "PermissionDenied"         => "AuthenticationError",
57        "AccountNotEnabled"        => "PermissionDenied",
58        "AccountSuspended"         => "AuthenticationError",
59        "ArgumentsRequired"        => "ExchangeError",
60        "BadRequest"               => "ExchangeError",
61        "BadSymbol"                => "BadRequest",
62        "OperationRejected"        => "ExchangeError",
63        "NoChange"                 => "OperationRejected",
64        "MarginModeAlreadySet"     => "NoChange",
65        "MarketClosed"             => "OperationRejected",
66        "ManualInteractionNeeded"  => "OperationRejected",
67        "RestrictedLocation"       => "OperationRejected",
68        "InsufficientFunds"        => "ExchangeError",
69        "InvalidAddress"           => "ExchangeError",
70        "AddressPending"           => "InvalidAddress",
71        "InvalidOrder"             => "ExchangeError",
72        "OrderNotFound"            => "InvalidOrder",
73        "OrderNotCached"           => "InvalidOrder",
74        "OrderImmediatelyFillable" => "InvalidOrder",
75        "OrderNotFillable"         => "InvalidOrder",
76        "DuplicateOrderId"         => "InvalidOrder",
77        "ContractUnavailable"      => "InvalidOrder",
78        "NotSupported"             => "ExchangeError",
79        "InvalidProxySettings"     => "ExchangeError",
80        "ExchangeClosedByUser"     => "ExchangeError",
81        // BaseError → OperationFailed subtree
82        "OperationFailed"          => "BaseError",
83        "NetworkError"             => "OperationFailed",
84        "DDoSProtection"           => "NetworkError",
85        "RateLimitExceeded"        => "NetworkError",
86        "ExchangeNotAvailable"     => "NetworkError",
87        "OnMaintenance"            => "ExchangeNotAvailable",
88        "InvalidNonce"             => "NetworkError",
89        "ChecksumError"            => "InvalidNonce",
90        "RequestTimeout"           => "NetworkError",
91        "BadResponse"              => "OperationFailed",
92        "NullResponse"             => "BadResponse",
93        "CancelPending"            => "OperationFailed",
94        // BaseError → misc
95        "UnsubscribeError"         => "BaseError",
96        _ => return None,
97    })
98}
99
100#[cfg(test)]
101mod error_hierarchy_tests {
102    use super::ExchangeError;
103
104    #[test]
105    fn subclass_membership() {
106        let e = ExchangeError::new("BadSymbol", "x");
107        assert!(e.is("BadSymbol"));
108        assert!(e.is("BadRequest"));
109        assert!(e.is("ExchangeError"));
110        assert!(e.is("BaseError"));
111        assert!(!e.is("NetworkError"));
112
113        assert!(ExchangeError::new("RequestTimeout", "x").is("NetworkError"));
114        assert!(ExchangeError::new("OnMaintenance", "x").is("OperationFailed"));
115        assert!(!ExchangeError::new("AuthenticationError", "x").is("BadRequest"));
116        assert!(!ExchangeError::new("Unknown", "x").is("ExchangeError"));
117    }
118}
119
120// ── From conversions from common third-party error types ────────────────────
121
122impl From<reqwest::Error> for ExchangeError {
123    fn from(e: reqwest::Error) -> Self {
124        Self::new("NetworkError", e.to_string())
125    }
126}
127
128impl From<serde_json::Error> for ExchangeError {
129    fn from(e: serde_json::Error) -> Self {
130        Self::new("BadResponse", e.to_string())
131    }
132}
133
134impl From<std::num::ParseFloatError> for ExchangeError {
135    fn from(e: std::num::ParseFloatError) -> Self {
136        Self::new("BadResponse", e.to_string())
137    }
138}
139
140impl From<std::num::ParseIntError> for ExchangeError {
141    fn from(e: std::num::ParseIntError) -> Self {
142        Self::new("BadResponse", e.to_string())
143    }
144}
145
146impl From<url::ParseError> for ExchangeError {
147    fn from(e: url::ParseError) -> Self {
148        Self::new("BadRequest", e.to_string())
149    }
150}