nautilus_bybit/http/
error.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Error structures and enumerations for the Bybit integration.
17//!
18//! The JSON error schema is described in the Bybit documentation under
19//! *Error Codes* – <https://bybit-exchange.github.io/docs/v5/error>.
20//! The types below mirror that structure and are reused across the entire
21//! crate.
22
23use nautilus_network::http::HttpClientError;
24use serde::{Deserialize, Serialize};
25use thiserror::Error;
26
27/// Build error for query parameter validation.
28#[derive(Debug, Clone, Error)]
29pub enum BybitBuildError {
30    /// Missing required category.
31    #[error("Missing required category")]
32    MissingCategory,
33    /// Missing required symbol.
34    #[error("Missing required symbol")]
35    MissingSymbol,
36    /// Missing required interval.
37    #[error("Missing required interval")]
38    MissingInterval,
39    /// Invalid limit value.
40    #[error("Invalid limit: must be between 1 and 1000")]
41    InvalidLimit,
42    /// Invalid time range: `start` should be less than `end`.
43    #[error("Invalid time range: start ({start}) must be less than end ({end})")]
44    InvalidTimeRange { start: i64, end: i64 },
45    /// Both orderId and orderLinkId specified.
46    #[error("Cannot specify both 'orderId' and 'orderLinkId'")]
47    BothOrderIds,
48    /// Missing required order identifier.
49    #[error("Missing required order identifier (orderId or orderLinkId)")]
50    MissingOrderId,
51}
52
53/// Represents the JSON structure of an error response returned by the Bybit API.
54///
55/// # References
56/// - <https://bybit-exchange.github.io/docs/v5/error>
57#[derive(Clone, Debug, Deserialize, Serialize)]
58#[serde(rename_all = "camelCase")]
59pub struct BybitErrorResponse {
60    /// Error code returned by Bybit.
61    pub ret_code: i32,
62    /// A human-readable explanation of the error condition.
63    pub ret_msg: String,
64    /// Extended error information.
65    #[serde(default)]
66    pub ret_ext_info: Option<serde_json::Value>,
67}
68
69/// A typed error enumeration for the Bybit HTTP client.
70#[derive(Debug, Clone, Error)]
71pub enum BybitHttpError {
72    /// Error variant when credentials are missing but the request is authenticated.
73    #[error("Missing credentials for authenticated request")]
74    MissingCredentials,
75    /// Errors returned directly by Bybit (non-zero code).
76    #[error("Bybit error {error_code}: {message}")]
77    BybitError { error_code: i32, message: String },
78    /// Failure during JSON serialization/deserialization.
79    #[error("JSON error: {0}")]
80    JsonError(String),
81    /// Parameter validation error.
82    #[error("Parameter validation error: {0}")]
83    ValidationError(String),
84    /// Build error for query parameters.
85    #[error("Build error: {0}")]
86    BuildError(#[from] BybitBuildError),
87    /// Request was canceled, typically due to shutdown or disconnect.
88    #[error("Request canceled: {0}")]
89    Canceled(String),
90    /// Generic network error (for retries, cancellations, etc).
91    #[error("Network error: {0}")]
92    NetworkError(String),
93    /// Any unknown HTTP status or unexpected response from Bybit.
94    #[error("Unexpected HTTP status code {status}: {body}")]
95    UnexpectedStatus { status: u16, body: String },
96}
97
98impl From<HttpClientError> for BybitHttpError {
99    fn from(error: HttpClientError) -> Self {
100        Self::NetworkError(error.to_string())
101    }
102}
103
104impl From<String> for BybitHttpError {
105    fn from(error: String) -> Self {
106        Self::ValidationError(error)
107    }
108}
109
110// Allow use of the `?` operator on `serde_json` results inside the HTTP
111// client implementation by converting them into our typed error.
112impl From<serde_json::Error> for BybitHttpError {
113    fn from(error: serde_json::Error) -> Self {
114        Self::JsonError(error.to_string())
115    }
116}
117
118impl From<BybitErrorResponse> for BybitHttpError {
119    fn from(error: BybitErrorResponse) -> Self {
120        Self::BybitError {
121            error_code: error.ret_code,
122            message: error.ret_msg,
123        }
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use rstest::rstest;
130
131    use super::*;
132
133    #[rstest]
134    fn test_bybit_build_error_display() {
135        let error = BybitBuildError::MissingSymbol;
136        assert_eq!(error.to_string(), "Missing required symbol");
137
138        let error = BybitBuildError::InvalidLimit;
139        assert_eq!(
140            error.to_string(),
141            "Invalid limit: must be between 1 and 1000"
142        );
143
144        let error = BybitBuildError::InvalidTimeRange {
145            start: 100,
146            end: 50,
147        };
148        assert_eq!(
149            error.to_string(),
150            "Invalid time range: start (100) must be less than end (50)"
151        );
152    }
153
154    #[rstest]
155    fn test_bybit_http_error_from_error_response() {
156        let error_response = BybitErrorResponse {
157            ret_code: 10001,
158            ret_msg: "Parameter error".to_string(),
159            ret_ext_info: None,
160        };
161
162        let http_error: BybitHttpError = error_response.into();
163        assert_eq!(http_error.to_string(), "Bybit error 10001: Parameter error");
164    }
165
166    #[rstest]
167    fn test_bybit_http_error_from_json_error() {
168        let json_err = serde_json::from_str::<BybitErrorResponse>("invalid json").unwrap_err();
169        let http_error: BybitHttpError = json_err.into();
170        assert!(http_error.to_string().contains("JSON error"));
171    }
172
173    #[rstest]
174    fn test_bybit_http_error_from_string() {
175        let error_msg = "Invalid parameter value".to_string();
176        let http_error: BybitHttpError = error_msg.into();
177        assert_eq!(
178            http_error.to_string(),
179            "Parameter validation error: Invalid parameter value"
180        );
181    }
182
183    #[rstest]
184    fn test_unexpected_status_error() {
185        let error = BybitHttpError::UnexpectedStatus {
186            status: 502,
187            body: "Server error".to_string(),
188        };
189        assert_eq!(
190            error.to_string(),
191            "Unexpected HTTP status code 502: Server error"
192        );
193    }
194}