Skip to main content

amberjs/error/
types.rs

1// Stage 89 Phase 2: 统一错误处理类型定义
2// 提供完整的错误分类、上下文信息和恢复建议
3
4use std::collections::HashMap;
5use std::fmt;
6use thiserror::Error;
7
8/// 错误类型枚举 - 统一所有可能的错误
9#[derive(Debug, Error, Clone, PartialEq)]
10pub enum AmberError {
11    #[error("V8 Error: {0}")]
12    V8Error(String),
13    #[error("JavaScript Execution Error: {0}")]
14    JsExecutionError(String),
15    #[error("Multi-language Error: {0}")]
16    MultiLanguageError(String),
17    #[error("Platform Error: {0}")]
18    PlatformError(String),
19    #[error("Compilation Error: {0}")]
20    CompilationError(String),
21    #[error("Runtime Error: {0}")]
22    RuntimeError(String),
23    #[error("Security Error: {0}")]
24    SecurityError(String),
25    #[error("Performance Error: {0}")]
26    PerformanceError(String),
27    #[error("Network Error: {0}")]
28    NetworkError(String),
29    #[error("IO Error: {0}")]
30    IoError(String),
31    #[error("Configuration Error: {0}")]
32    ConfigurationError(String),
33    #[error("Resource Error: {0}")]
34    ResourceError(String),
35}
36/// 源代码位置信息
37#[derive(Debug, Clone, PartialEq)]
38pub struct SourceLocation {
39    pub file: String,
40    pub line: u32,
41    pub column: Option<u32>,
42    pub function: String,
43}
44impl SourceLocation {
45    pub fn new(file: String, line: u32, function: String) -> Self {
46        Self {
47            file,
48            line,
49            column: None,
50            function,
51        }
52    }
53    pub fn with_column(mut self, column: u32) -> Self {
54        self.column = Some(column);
55        self
56    }
57    pub fn to_string(&self) -> String {
58        if let Some(col) = self.column {
59            format!("{}:{}:{}", self.file, self.line, col)
60        } else {
61            format!("{}:{}", self.file, self.line)
62        }
63    }
64}
65/// 栈帧信息
66#[derive(Debug, Clone, PartialEq)]
67pub struct StackFrame {
68    pub function: String,
69    pub file: String,
70    pub line: u32,
71    pub column: Option<u32>,
72}
73/// 错误严重级别
74#[derive(Debug, Clone, PartialEq)]
75pub enum ErrorSeverity {
76    Low,      // 轻微错误,不影响主要功能
77    Medium,   // 中等错误,部分功能受影响
78    High,     // 严重错误,主要功能受影响
79    Critical, // 关键错误,系统可能崩溃
80}
81impl fmt::Display for ErrorSeverity {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            ErrorSeverity::Low => write!(f, "LOW"),
85            ErrorSeverity::Medium => write!(f, "MEDIUM"),
86            ErrorSeverity::High => write!(f, "HIGH"),
87            ErrorSeverity::Critical => write!(f, "CRITICAL"),
88        }
89    }
90}
91/// 错误上下文 - 提供完整的错误上下文信息
92#[derive(Debug, Clone)]
93pub struct ErrorContext {
94    pub error_type: AmberError,
95    pub source_location: Option<SourceLocation>,
96    pub stack_trace: Vec<StackFrame>,
97    pub severity: ErrorSeverity,
98    pub timestamp: std::time::Instant,
99    pub recovery_suggestions: Vec<String>,
100    pub metadata: HashMap<String, String>,
101}
102impl ErrorContext {
103    /// 创建新的错误上下文
104    pub fn new(error_type: AmberError, file: String, line: u32, function: String) -> Self {
105        let source_location: _ = Some(SourceLocation::new(file, line, function));
106        let severity: _ = Self::determine_severity(&error_type);
107        let recovery_suggestions: _ = Self::generate_recovery_suggestions(&error_type);
108        Self {
109            error_type,
110            source_location,
111            stack_trace: Vec::new(),
112            severity,
113            timestamp: std::time::Instant::now(),
114            recovery_suggestions,
115            metadata: HashMap::new(),
116        }
117    }
118    /// 创建无源位置的错误上下文
119    pub fn new_without_location(error_type: AmberError) -> Self {
120        let severity: _ = Self::determine_severity(&error_type);
121        let recovery_suggestions: _ = Self::generate_recovery_suggestions(&error_type);
122        Self {
123            error_type,
124            source_location: None,
125            stack_trace: Vec::new(),
126            severity,
127            timestamp: std::time::Instant::now(),
128            recovery_suggestions,
129            metadata: HashMap::new(),
130        }
131    }
132    /// 根据错误类型确定严重级别
133    fn determine_severity(error: &AmberError) -> ErrorSeverity {
134        match error {
135            AmberError::V8Error(_) | AmberError::JsExecutionError(_) => ErrorSeverity::High,
136            AmberError::MultiLanguageError(_) | AmberError::PlatformError(_) => {
137                ErrorSeverity::Medium
138            }
139            AmberError::CompilationError(_) | AmberError::RuntimeError(_) => ErrorSeverity::High,
140            AmberError::SecurityError(_) => ErrorSeverity::Critical,
141            AmberError::PerformanceError(_) | AmberError::NetworkError(_) => ErrorSeverity::Medium,
142            AmberError::IoError(_) | AmberError::ConfigurationError(_) => ErrorSeverity::Low,
143            AmberError::ResourceError(_) => ErrorSeverity::Medium,
144        }
145    }
146    /// 生成恢复建议
147    fn generate_recovery_suggestions(error: &AmberError) -> Vec<String> {
148        match error {
149            AmberError::V8Error(_) => vec![
150                "Check V8 version compatibility".to_string(),
151                "Verify isolate state".to_string(),
152                "Review API usage".to_string(),
153            ],
154            AmberError::JsExecutionError(_) => vec![
155                "Check JavaScript syntax".to_string(),
156                "Verify variable types".to_string(),
157                "Review function calls".to_string(),
158            ],
159            AmberError::MultiLanguageError(_) => vec![
160                "Initialize runtime before use".to_string(),
161                "Check module imports".to_string(),
162                "Verify language bindings".to_string(),
163            ],
164            AmberError::PlatformError(_) => vec![
165                "Check platform compatibility".to_string(),
166                "Verify runtime installation".to_string(),
167                "Review platform-specific code".to_string(),
168            ],
169            AmberError::CompilationError(_) => vec![
170                "Fix syntax errors".to_string(),
171                "Check type definitions".to_string(),
172                "Review import statements".to_string(),
173            ],
174            AmberError::RuntimeError(_) => vec![
175                "Check runtime state".to_string(),
176                "Verify resource availability".to_string(),
177                "Review execution flow".to_string(),
178            ],
179            AmberError::SecurityError(_) => vec![
180                "Check security policies".to_string(),
181                "Verify permissions".to_string(),
182                "Review access controls".to_string(),
183            ],
184            AmberError::PerformanceError(_) => vec![
185                "Optimize resource usage".to_string(),
186                "Check memory allocation".to_string(),
187                "Review performance bottlenecks".to_string(),
188            ],
189            AmberError::NetworkError(_) => vec![
190                "Check network connectivity".to_string(),
191                "Verify URL/endpoint".to_string(),
192                "Review timeout settings".to_string(),
193            ],
194            AmberError::IoError(_) => vec![
195                "Check file/directory permissions".to_string(),
196                "Verify path existence".to_string(),
197                "Review I/O operations".to_string(),
198            ],
199            AmberError::ConfigurationError(_) => vec![
200                "Check configuration file".to_string(),
201                "Verify configuration values".to_string(),
202                "Review environment variables".to_string(),
203            ],
204            AmberError::ResourceError(_) => vec![
205                "Check resource availability".to_string(),
206                "Optimize resource usage".to_string(),
207                "Review resource limits".to_string(),
208            ],
209        }
210    }
211    /// 添加栈帧信息
212    pub fn add_stack_frame(&mut self, frame: StackFrame) {
213        self.stack_trace.push(frame);
214    }
215    /// 添加元数据
216    pub fn add_metadata(&mut self, key: String, value: String) {
217        self.metadata.insert(key, value);
218    }
219    /// 获取恢复建议
220    pub fn get_recovery_suggestions(&self) -> Vec<String> {
221        self.recovery_suggestions.clone()
222    }
223    /// 获取错误持续时间
224    pub fn get_duration(&self) -> std::time::Duration {
225        self.timestamp.elapsed()
226    }
227}
228impl fmt::Display for ErrorContext {
229    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
230        write!(
231            f,
232            "Error: {} (Severity: {})",
233            self.error_type, self.severity
234        )?;
235        if let Some(ref loc) = self.source_location {
236            write!(f, " at {}", loc.to_string())?;
237        }
238        if !self.recovery_suggestions.is_empty() {
239            write!(f, "\nSuggestions:")?;
240            for suggestion in &self.recovery_suggestions {
241                write!(f, "\n  - {}", suggestion)?;
242            }
243        }
244        Ok(())
245    }
246}