postfix_log_parser/
error.rs

1use crate::events::PostfixLogEvent;
2use thiserror::Error;
3
4/// 解析错误类型
5#[derive(Error, Debug, Clone)]
6pub enum ParseError {
7    #[error("无法识别的组件: {component}")]
8    UnknownComponent { component: String },
9
10    #[error("无效的时间戳格式: {timestamp}")]
11    InvalidTimestamp { timestamp: String },
12
13    #[error("无效的日志格式: {reason}")]
14    InvalidLogFormat { reason: String },
15
16    #[error("组件解析失败: {component} - {reason}")]
17    ComponentParseError { component: String, reason: String },
18
19    #[error("正则表达式错误: {0}")]
20    RegexError(#[from] regex::Error),
21
22    #[error("日期时间解析错误: {0}")]
23    ChronoParseError(#[from] chrono::ParseError),
24}
25
26/// 解析结果
27///
28/// 包含解析得到的事件、置信度和可能的错误信息
29#[derive(Debug, Clone)]
30pub struct ParseResult {
31    /// 解析得到的事件,如果解析失败则为 None
32    pub event: Option<PostfixLogEvent>,
33
34    /// 解析置信度 (0.0 - 1.0)
35    /// - 1.0: 完全匹配
36    /// - 0.7-0.9: 模糊匹配
37    /// - 0.3-0.6: 部分解析
38    /// - 0.0-0.2: 解析失败
39    pub confidence: f32,
40
41    /// 解析过程中的错误和警告信息
42    pub parsing_errors: Vec<String>,
43}
44
45impl ParseResult {
46    /// 创建成功的解析结果
47    pub fn success(event: PostfixLogEvent, confidence: f32) -> Self {
48        Self {
49            event: Some(event),
50            confidence,
51            parsing_errors: Vec::new(),
52        }
53    }
54
55    /// 创建失败的解析结果
56    pub fn failure(error: ParseError) -> Self {
57        Self {
58            event: None,
59            confidence: 0.0,
60            parsing_errors: vec![error.to_string()],
61        }
62    }
63
64    /// 创建部分成功的解析结果
65    pub fn partial(event: PostfixLogEvent, confidence: f32, warnings: Vec<String>) -> Self {
66        Self {
67            event: Some(event),
68            confidence,
69            parsing_errors: warnings,
70        }
71    }
72
73    /// 检查解析是否成功
74    pub fn is_success(&self) -> bool {
75        self.event.is_some() && self.confidence > 0.5
76    }
77
78    /// 检查解析是否完全失败
79    pub fn is_failure(&self) -> bool {
80        self.event.is_none()
81    }
82
83    /// 获取主要错误(如果有的话)
84    pub fn main_error(&self) -> Option<&String> {
85        self.parsing_errors.first()
86    }
87}