use thiserror::Error;
fn display_api_error(status: u16, body: &str) -> String {
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body) {
if let Some(msg) = parsed
.get("message")
.or_else(|| parsed.get("detail"))
.and_then(|val| val.as_str())
{
return format!("API error ({status}): {msg}");
}
if let Some(msg) = parsed
.get("error")
.and_then(|err| err.get("message"))
.and_then(|val| val.as_str())
{
return format!("API error ({status}): {msg}");
}
}
format!("API error ({status}): {body}")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChallengeType {
Sms,
Email,
Prompt,
}
impl std::fmt::Display for ChallengeType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Sms => write!(f, "SMS"),
Self::Email => write!(f, "email"),
Self::Prompt => write!(f, "app prompt"),
}
}
}
#[derive(Debug, Error)]
pub enum RhoodError {
#[error("Not authenticated, run `rhood login` first")]
NotAuthenticated,
#[error("Authentication challenge required: {0}")]
ChallengeRequired(ChallengeType),
#[error("Token expired and refresh failed")]
TokenExpired,
#[error("{}", display_api_error(*.status, message))]
Api {
status: u16,
message: String,
},
#[error("Rate limited, retry after {retry_after_secs}s")]
RateLimited {
retry_after_secs: u64,
},
#[error("Symbol not found: {0}")]
InvalidSymbol(String),
#[error("Invalid parameter: {0}")]
InvalidParameter(String),
#[error("Operation blocked, client is in read-only mode")]
ReadOnlyMode,
#[error("Invalid order: {0}")]
InvalidOrder(String),
#[error("Device verification required, run `rhood login` interactively first")]
DeviceVerificationRequired,
#[error(transparent)]
Http(#[from] reqwest::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Timeout: {0}")]
Timeout(String),
}
#[cfg(test)]
mod tests {
use super::RhoodError;
#[test]
fn rhood_error_display_messages() {
let err = RhoodError::NotAuthenticated;
assert!(err.to_string().contains("Not authenticated"));
let err = RhoodError::ReadOnlyMode;
assert!(err.to_string().contains("read-only"));
let err = RhoodError::InvalidSymbol("XYZ".into());
assert!(err.to_string().contains("XYZ"));
let err = RhoodError::RateLimited {
retry_after_secs: 30,
};
assert!(err.to_string().contains("30"));
let err = RhoodError::Api {
status: 404,
message: "Not found".into(),
};
assert!(err.to_string().contains("404"));
assert!(err.to_string().contains("Not found"));
}
#[test]
fn api_error_display_extracts_json_message() {
let err = RhoodError::Api {
status: 404,
message: r#"{"code":5,"message":"futures contract not found","details":[]}"#.into(),
};
let display = err.to_string();
assert_eq!(display, "API error (404): futures contract not found");
}
#[test]
fn api_error_display_extracts_nested_error_message() {
let err = RhoodError::Api {
status: 400,
message: r#"{"status":"FAILURE","error":{"code":3,"message":"invalid argument"}}"#
.into(),
};
let display = err.to_string();
assert_eq!(display, "API error (400): invalid argument");
}
#[test]
fn api_error_display_extracts_detail_field() {
let err = RhoodError::Api {
status: 403,
message: r#"{"detail":"Permission denied"}"#.into(),
};
assert_eq!(err.to_string(), "API error (403): Permission denied");
}
#[test]
fn api_error_display_falls_back_to_raw_body() {
let err = RhoodError::Api {
status: 500,
message: "Internal server error".into(),
};
assert_eq!(err.to_string(), "API error (500): Internal server error");
}
}