nautilus_dydx/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 dYdX integration.
17//!
18//! The dYdX v4 Indexer API error responses are typically returned with
19//! appropriate HTTP status codes and error messages in the response body.
20
21use serde::Deserialize;
22use thiserror::Error;
23
24/// Represents a build error for query parameter validation.
25#[derive(Debug, Error)]
26pub enum BuildError {
27    /// Missing required address parameter.
28    #[error("Missing required address parameter")]
29    MissingAddress,
30    /// Missing required market ticker parameter.
31    #[error("Missing required market ticker parameter")]
32    MissingTicker,
33    /// Missing required subaccount number.
34    #[error("Missing required subaccount number")]
35    MissingSubaccountNumber,
36    /// Both createdBeforeOrAt and createdBeforeOrAtHeight specified.
37    #[error("Cannot specify both 'createdBeforeOrAt' and 'createdBeforeOrAtHeight' parameters")]
38    BothCreatedBeforeParams,
39    /// Both createdOnOrAfter and createdOnOrAfterHeight specified.
40    #[error("Cannot specify both 'createdOnOrAfter' and 'createdOnOrAfterHeight' parameters")]
41    BothCreatedAfterParams,
42    /// Invalid time range.
43    #[error("Invalid time range: from_iso must be before to_iso")]
44    InvalidTimeRange,
45    /// Limit exceeds maximum allowed value.
46    #[error("Limit exceeds maximum allowed value")]
47    LimitTooHigh,
48    /// Invalid resolution parameter.
49    #[error("Invalid resolution parameter: {0}")]
50    InvalidResolution(String),
51}
52
53/// Represents the JSON structure of an error response returned by the dYdX Indexer API.
54#[derive(Clone, Debug, Deserialize)]
55pub struct DydxErrorResponse {
56    /// HTTP status code.
57    #[serde(default)]
58    pub status: Option<u16>,
59    /// Error message describing what went wrong.
60    pub message: String,
61    /// Additional error details if provided.
62    #[serde(default)]
63    pub details: Option<String>,
64}
65
66/// A typed error enumeration for the dYdX HTTP client.
67#[derive(Debug, Error)]
68pub enum DydxHttpError {
69    /// Errors returned by the dYdX Indexer API with a specific HTTP status.
70    #[error("dYdX API error {status}: {message}")]
71    HttpStatus { status: u16, message: String },
72    /// Failure during JSON serialization.
73    #[error("Serialization error: {error}")]
74    Serialization { error: String },
75    /// Failure during JSON deserialization.
76    #[error("Deserialization error: {error}, body: {body}")]
77    Deserialization { error: String, body: String },
78    /// Parameter validation error.
79    #[error("Parameter validation error: {0}")]
80    ValidationError(String),
81    /// Request was canceled, typically due to shutdown or disconnect.
82    #[error("Request canceled: {0}")]
83    Canceled(String),
84    /// Wrapping the underlying HttpClientError from the network crate.
85    #[error("Network error: {0}")]
86    HttpClientError(String),
87    /// Any unknown HTTP status or unexpected response from dYdX.
88    #[error("Unexpected HTTP status code {status}: {body}")]
89    UnexpectedStatus { status: u16, body: String },
90}
91
92impl From<String> for DydxHttpError {
93    fn from(error: String) -> Self {
94        Self::ValidationError(error)
95    }
96}
97
98impl From<BuildError> for DydxHttpError {
99    fn from(error: BuildError) -> Self {
100        Self::ValidationError(error.to_string())
101    }
102}
103
104////////////////////////////////////////////////////////////////////////////////
105// Tests
106////////////////////////////////////////////////////////////////////////////////
107
108#[cfg(test)]
109mod tests {
110    use rstest::rstest;
111
112    use super::*;
113
114    #[rstest]
115    fn test_build_error_display() {
116        let error = BuildError::MissingAddress;
117        assert_eq!(error.to_string(), "Missing required address parameter");
118
119        let error = BuildError::MissingTicker;
120        assert_eq!(
121            error.to_string(),
122            "Missing required market ticker parameter"
123        );
124    }
125
126    #[rstest]
127    fn test_dydx_http_error_from_string() {
128        let error: DydxHttpError = "Invalid parameter".to_string().into();
129        match error {
130            DydxHttpError::ValidationError(msg) => assert_eq!(msg, "Invalid parameter"),
131            _ => panic!("Expected ValidationError"),
132        }
133    }
134
135    #[rstest]
136    fn test_dydx_http_error_from_build_error() {
137        let build_error = BuildError::MissingSubaccountNumber;
138        let http_error: DydxHttpError = build_error.into();
139        match http_error {
140            DydxHttpError::ValidationError(msg) => {
141                assert_eq!(msg, "Missing required subaccount number");
142            }
143            _ => panic!("Expected ValidationError"),
144        }
145    }
146}