Skip to main content

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