ctp_rust/
error.rs

1//! 错误处理模块
2//!
3//! 定义了CTP SDK中使用的错误类型和结果类型
4
5use std::fmt;
6
7/// CTP错误类型
8#[derive(Debug, Clone)]
9pub enum CtpError {
10    /// FFI调用错误
11    FfiError(String),
12    /// 编码转换错误
13    EncodingError(String),
14    /// 网络连接错误
15    ConnectionError(String),
16    /// 登录认证错误
17    AuthenticationError(String),
18    /// 业务逻辑错误
19    BusinessError(i32, String),
20    /// 初始化错误
21    InitializationError(String),
22    /// 超时错误
23    TimeoutError(String),
24    /// 无效参数错误
25    InvalidParameterError(String),
26    /// 内存错误
27    MemoryError(String),
28    /// 其他错误
29    Other(String),
30}
31
32impl fmt::Display for CtpError {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            CtpError::FfiError(msg) => write!(f, "FFI错误: {}", msg),
36            CtpError::EncodingError(msg) => write!(f, "编码转换错误: {}", msg),
37            CtpError::ConnectionError(msg) => write!(f, "网络连接错误: {}", msg),
38            CtpError::AuthenticationError(msg) => write!(f, "登录认证错误: {}", msg),
39            CtpError::BusinessError(code, msg) => write!(f, "业务错误 [{}]: {}", code, msg),
40            CtpError::InitializationError(msg) => write!(f, "初始化错误: {}", msg),
41            CtpError::TimeoutError(msg) => write!(f, "超时错误: {}", msg),
42            CtpError::InvalidParameterError(msg) => write!(f, "无效参数错误: {}", msg),
43            CtpError::MemoryError(msg) => write!(f, "内存错误: {}", msg),
44            CtpError::Other(msg) => write!(f, "其他错误: {}", msg),
45        }
46    }
47}
48
49impl std::error::Error for CtpError {}
50
51/// CTP结果类型
52pub type CtpResult<T> = Result<T, CtpError>;
53
54/// 将C字符串错误转换为CtpError
55pub fn c_string_error(msg: &str) -> CtpError {
56    CtpError::FfiError(format!("C字符串处理错误: {}", msg))
57}
58
59/// 将编码错误转换为CtpError
60pub fn encoding_error(msg: &str) -> CtpError {
61    CtpError::EncodingError(msg.to_string())
62}
63
64/// 将连接错误转换为CtpError
65pub fn connection_error(msg: &str) -> CtpError {
66    CtpError::ConnectionError(msg.to_string())
67}
68
69/// 将业务错误转换为CtpError
70pub fn business_error(error_id: i32, error_msg: &str) -> CtpError {
71    CtpError::BusinessError(error_id, error_msg.to_string())
72}