pcapfile_io/foundation/
error.rs

1use crate::foundation::types::PcapErrorCode;
2use thiserror::Error;
3
4/// PCAP操作错误
5#[derive(Error, Debug)]
6pub enum PcapError {
7    #[error("文件未找到: {0}")]
8    FileNotFound(String),
9
10    #[error("目录不存在: {0}")]
11    DirectoryNotFound(String),
12
13    #[error("无效的文件格式: {0}")]
14    InvalidFormat(String),
15
16    #[error("文件头损坏: {0}")]
17    CorruptedHeader(String),
18
19    #[error("数据包损坏: {message},位置 {position}")]
20    CorruptedData { message: String, position: u64 },
21
22    #[error(
23        "校验和不匹配: 期望 {expected}, 实际 {actual},位置 {position}"
24    )]
25    ChecksumMismatch {
26        expected: String,
27        actual: String,
28        position: u64,
29    },
30
31    #[error("数据包大小无效: {message},位置 {position}")]
32    InvalidPacketSize { message: String, position: u64 },
33
34    #[error("数据包长度超出文件剩余空间: 期望 {expected} 字节,剩余 {remaining} 字节,位置 {position}")]
35    PacketSizeExceedsRemainingBytes {
36        expected: u32,
37        remaining: u64,
38        position: u64,
39    },
40
41    #[error("时间戳解析错误: {message},位置 {position}")]
42    TimestampParseError { message: String, position: u64 },
43
44    #[error("参数无效: {0}")]
45    InvalidArgument(String),
46
47    #[error("操作状态无效: {0}")]
48    InvalidState(String),
49
50    #[error("IO错误: {0}")]
51    Io(#[from] std::io::Error),
52
53    #[error("序列化错误: {0}")]
54    Serialization(String),
55
56    #[error("未知错误: {0}")]
57    Unknown(String),
58}
59
60impl PcapError {
61    /// 获取错误代码
62    pub fn error_code(&self) -> PcapErrorCode {
63        match self {
64            PcapError::FileNotFound(_) => {
65                PcapErrorCode::FileNotFound
66            }
67            PcapError::DirectoryNotFound(_) => {
68                PcapErrorCode::DirectoryNotFound
69            }
70            PcapError::InvalidFormat(_) => {
71                PcapErrorCode::InvalidFormat
72            }
73            PcapError::CorruptedHeader(_) => {
74                PcapErrorCode::CorruptedHeader
75            }
76            PcapError::CorruptedData { .. } => {
77                PcapErrorCode::CorruptedData
78            }
79            PcapError::ChecksumMismatch { .. } => {
80                PcapErrorCode::ChecksumMismatch
81            }
82            PcapError::InvalidPacketSize { .. } => {
83                PcapErrorCode::InvalidPacketSize
84            }
85            PcapError::PacketSizeExceedsRemainingBytes { .. } => {
86                PcapErrorCode::PacketSizeExceedsRemainingBytes
87            }
88            PcapError::TimestampParseError { .. } => {
89                PcapErrorCode::TimestampParseError
90            }
91            PcapError::InvalidArgument(_) => {
92                PcapErrorCode::InvalidArgument
93            }
94            PcapError::InvalidState(_) => {
95                PcapErrorCode::InvalidState
96            }
97            PcapError::Io(_) => PcapErrorCode::Unknown,
98            PcapError::Serialization(_) => {
99                PcapErrorCode::InvalidFormat
100            }
101            PcapError::Unknown(_) => PcapErrorCode::Unknown,
102        }
103    }
104
105    /// 获取详细错误信息
106    pub fn detailed_message(&self) -> String {
107        format!(
108            "错误代码: {}, 错误信息: {}",
109            self.error_code(),
110            self
111        )
112    }
113}
114
115/// 结果类型别名
116pub type PcapResult<T> = std::result::Result<T, PcapError>;
117
118/// 从字符串错误转换为PcapError
119impl From<String> for PcapError {
120    fn from(err: String) -> Self {
121        PcapError::Unknown(err)
122    }
123}
124
125/// 从&str错误转换为PcapError
126impl From<&str> for PcapError {
127    fn from(err: &str) -> Self {
128        PcapError::Unknown(err.to_string())
129    }
130}
131
132/// 从serde_json错误转换为PcapError
133impl From<serde_json::Error> for PcapError {
134    fn from(err: serde_json::Error) -> Self {
135        PcapError::Serialization(err.to_string())
136    }
137}
138
139/// 从base64错误转换为PcapError
140impl From<base64::DecodeError> for PcapError {
141    fn from(err: base64::DecodeError) -> Self {
142        PcapError::InvalidFormat(format!(
143            "Base64解码失败: {err}"
144        ))
145    }
146}
147
148/// 从std::string::FromUtf8Error错误转换为PcapError
149impl From<std::string::FromUtf8Error> for PcapError {
150    fn from(err: std::string::FromUtf8Error) -> Self {
151        PcapError::InvalidFormat(format!(
152            "UTF8解码失败: {err}"
153        ))
154    }
155}
156
157/// 错误结果类型
158#[derive(Debug, Clone)]
159pub struct ErrorResult {
160    pub success: bool,
161    pub error_message: Option<String>,
162    pub error_code: Option<PcapErrorCode>,
163}
164
165impl ErrorResult {
166    /// 创建成功结果
167    pub fn success() -> Self {
168        Self {
169            success: true,
170            error_message: None,
171            error_code: None,
172        }
173    }
174
175    /// 创建失败结果
176    pub fn failure(
177        error_message: String,
178        error_code: Option<PcapErrorCode>,
179    ) -> Self {
180        Self {
181            success: false,
182            error_message: Some(error_message),
183            error_code,
184        }
185    }
186
187    /// 从PcapError创建失败结果
188    pub fn from_error(error: PcapError) -> Self {
189        Self::failure(
190            error.to_string(),
191            Some(error.error_code()),
192        )
193    }
194}
195
196impl std::fmt::Display for ErrorResult {
197    fn fmt(
198        &self,
199        f: &mut std::fmt::Formatter<'_>,
200    ) -> std::fmt::Result {
201        if self.success {
202            write!(f, "操作成功")
203        } else {
204            write!(
205                f,
206                "操作失败: {} (错误代码: {:?})",
207                self.error_message
208                    .as_deref()
209                    .unwrap_or("未知错误"),
210                self.error_code
211            )
212        }
213    }
214}