ccxt_core/error/
convert.rs

1//! From implementations for converting between error types.
2
3use crate::error::{ConfigValidationError, Error, NetworkError, OrderError, ParseError};
4
5/// Maximum length for error messages to prevent memory bloat from large HTTP responses.
6pub(crate) const MAX_ERROR_MESSAGE_LEN: usize = 1024;
7
8/// Truncates a string to a maximum length, adding "... (truncated)" if needed.
9pub(crate) fn truncate_message(mut msg: String) -> String {
10    if msg.len() > MAX_ERROR_MESSAGE_LEN {
11        msg.truncate(MAX_ERROR_MESSAGE_LEN);
12        msg.push_str("... (truncated)");
13    }
14    msg
15}
16
17impl From<NetworkError> for Error {
18    fn from(e: NetworkError) -> Self {
19        Error::Network(Box::new(e))
20    }
21}
22
23impl From<Box<NetworkError>> for Error {
24    fn from(e: Box<NetworkError>) -> Self {
25        Error::Network(e)
26    }
27}
28
29impl From<ParseError> for Error {
30    fn from(e: ParseError) -> Self {
31        Error::Parse(Box::new(e))
32    }
33}
34
35impl From<Box<ParseError>> for Error {
36    fn from(e: Box<ParseError>) -> Self {
37        Error::Parse(e)
38    }
39}
40
41impl From<OrderError> for Error {
42    fn from(e: OrderError) -> Self {
43        Error::Order(Box::new(e))
44    }
45}
46
47impl From<Box<OrderError>> for Error {
48    fn from(e: Box<OrderError>) -> Self {
49        Error::Order(e)
50    }
51}
52
53impl From<serde_json::Error> for Error {
54    fn from(e: serde_json::Error) -> Self {
55        Error::Parse(Box::new(ParseError::Json(e)))
56    }
57}
58
59impl From<rust_decimal::Error> for Error {
60    fn from(e: rust_decimal::Error) -> Self {
61        Error::Parse(Box::new(ParseError::Decimal(e)))
62    }
63}
64
65impl From<reqwest::Error> for NetworkError {
66    fn from(e: reqwest::Error) -> Self {
67        if e.is_timeout() {
68            NetworkError::Timeout
69        } else if e.is_connect() {
70            NetworkError::ConnectionFailed(truncate_message(e.to_string()))
71        } else if let Some(status) = e.status() {
72            NetworkError::RequestFailed {
73                status: status.as_u16(),
74                message: truncate_message(e.to_string()),
75            }
76        } else {
77            NetworkError::Transport(Box::new(e))
78        }
79    }
80}
81
82impl From<reqwest::Error> for Error {
83    fn from(e: reqwest::Error) -> Self {
84        Error::Network(Box::new(NetworkError::from(e)))
85    }
86}
87
88impl From<ConfigValidationError> for Error {
89    fn from(e: ConfigValidationError) -> Self {
90        Error::ConfigValidation(Box::new(e))
91    }
92}
93
94impl From<Box<ConfigValidationError>> for Error {
95    fn from(e: Box<ConfigValidationError>) -> Self {
96        Error::ConfigValidation(e)
97    }
98}