# Office-RS 错误处理系统指南
本指南详细介绍了 office-rs 库的高级错误处理功能,包括错误上下文、错误码、恢复建议、错误监控等特性。
## 🚀 新增功能概览
### 1. 错误上下文 (ErrorContext)
为错误提供详细的上下文信息,帮助开发者快速定位问题:
```rust
use office_rs::error::{DocumentError, ErrorContext};
let context = ErrorContext {
file_path: Some("workbook.xlsx".to_string()),
line_number: Some(42),
element_path: Some("/workbook/worksheet[1]/row[5]/cell[3]".to_string()),
operation: Some("读取单元格值".to_string()),
};
let error = DocumentError::file_not_found_with_context(
"missing_file.xlsx".to_string(),
context
);
```
### 2. 错误码系统 (ErrorCode)
提供结构化的错误码,便于程序化处理:
```rust
use office_rs::error::ErrorCode;
let error_code = error.error_code();
match error_code {
ErrorCode::FileNotFound => {
// 处理文件未找到错误
},
ErrorCode::XlsxWorksheetNotFound => {
// 处理工作表未找到错误
},
_ => {
// 其他错误处理
}
}
```
#### 错误码分类
- **文件系统错误 (1000-1999)**
- `FileNotFound` (1001)
- `FilePermissionDenied` (1002)
- `FileCorrupted` (1003)
- `FileInvalidFormat` (1004)
- **IO错误 (1100-1199)**
- `IoError` (1100)
- `ZipError` (1101)
- **解析错误 (2000-2999)**
- `XmlParseError` (2001)
- `JsonParseError` (2002)
- `EncodingError` (2003)
- `MissingElement` (2004)
- `InvalidAttribute` (2005)
- `UnsupportedVersion` (2006)
- `InvalidNamespace` (2007)
- **Excel错误 (3000-3999)**
- `XlsxWorksheetNotFound` (3001)
- `XlsxInvalidCellReference` (3002)
- `XlsxInvalidFormula` (3003)
- `XlsxInvalidStyleId` (3004)
- `XlsxSharedStringIndexOutOfRange` (3005)
- **Word错误 (4000-4999)**
- `DocxStyleNotFound` (4001)
- `DocxInvalidTableStructure` (4002)
- `DocxInvalidParagraphFormat` (4003)
- `DocxBookmarkNotFound` (4004)
- **PowerPoint错误 (5000-5999)**
- `PptxSlideNotFound` (5001)
- `PptxLayoutNotFound` (5002)
- `PptxInvalidShapeId` (5003)
- `PptxInvalidAnimation` (5004)
### 3. 错误恢复建议 (RecoverySuggestion)
为每种错误提供智能的恢复建议:
```rust
use office_rs::error::RecoveryAction;
if let Some(suggestion) = error.recovery_suggestion() {
println!("建议: {}", suggestion.message);
match suggestion.action {
RecoveryAction::UseDefault => {
// 使用默认值继续处理
},
RecoveryAction::SkipElement => {
// 跳过当前元素
},
RecoveryAction::Retry => {
// 重试操作
},
RecoveryAction::UserInput(msg) => {
// 需要用户输入
println!("需要用户操作: {}", msg);
},
RecoveryAction::None => {
// 无法恢复
}
}
}
```
### 4. 错误监控和统计 (ErrorMonitor)
自动收集和分析错误统计信息:
```rust
use office_rs::error::error_monitor;
// 获取错误统计
let stats = error_monitor().get_stats();
for stat in stats {
println!("错误码: {:?}, 发生次数: {}", stat.error_code, stat.count);
}
// 获取最常见的错误
let common_errors = error_monitor().most_common_errors(5);
// 获取总错误数
let total = error_monitor().total_errors();
```
### 5. 错误链分析
提供完整的错误链分析功能:
```rust
// 获取错误链
let error_chain = error.error_chain();
for (i, err) in error_chain.iter().enumerate() {
println!("{}. {}", i + 1, err);
}
// 获取根因错误
let root_cause = error.root_cause();
// 获取根错误(去除上下文包装)
let root_error = error.root_error();
```
## 🛠️ 使用最佳实践
### 1. 创建带上下文的错误
```rust
use office_rs::error::{DocumentError, ErrorContext};
fn read_worksheet(file_path: &str, sheet_name: &str) -> office_rs::Result<()> {
let context = ErrorContext {
file_path: Some(file_path.to_string()),
operation: Some(format!("读取工作表: {}", sheet_name)),
..Default::default()
};
// 如果工作表不存在
Err(DocumentError::xlsx_error_with_context(
sheet_name.to_string(),
context
))
}
```
### 2. 错误处理和恢复
```rust
fn handle_error_with_recovery(error: &DocumentError) {
// 记录错误(如果还没有记录)
error.record();
// 获取恢复建议
if let Some(suggestion) = error.recovery_suggestion() {
match suggestion.action {
RecoveryAction::UseDefault => {
// 使用默认值继续处理
println!("使用默认值: {}", suggestion.message);
},
RecoveryAction::Retry => {
// 可以重试操作
println!("可以重试: {}", suggestion.message);
},
_ => {
println!("其他建议: {}", suggestion.message);
}
}
}
}
```
### 3. 错误监控集成
```rust
use office_rs::error::error_monitor;
// 在应用程序启动时
fn setup_error_monitoring() {
// 清除之前的统计(可选)
error_monitor().clear_stats();
}
// 定期检查错误统计
fn check_error_stats() {
let total_errors = error_monitor().total_errors();
if total_errors > 100 {
println!("警告: 错误数量过多 ({})", total_errors);
// 分析最常见的错误
let common = error_monitor().most_common_errors(3);
for (i, stat) in common.iter().enumerate() {
println!("{}. {:?}: {}次", i + 1, stat.error_code, stat.count);
}
}
}
```
## 📊 错误分类和严重程度
### 错误分类 (ErrorCategory)
- `FileSystem`: 文件系统相关错误
- `Parsing`: 解析相关错误
- `Validation`: 验证相关错误
- `Internal`: 内部错误
### 错误严重程度 (ErrorSeverity)
- `Fatal`: 致命错误,无法继续处理
- `Error`: 一般错误,可能影响功能
- `Warning`: 警告,不影响主要功能
```rust
let severity = error.severity();
let category = error.category();
let is_recoverable = error.is_recoverable();
match severity {
ErrorSeverity::Fatal => {
// 停止处理,返回错误
},
ErrorSeverity::Error => {
// 尝试恢复或使用默认值
},
ErrorSeverity::Warning => {
// 记录警告,继续处理
}
}
```
## 🔧 便捷构造函数
库提供了多个便捷的错误构造函数:
```rust
// 文件未找到错误
let error = DocumentError::file_not_found_with_context(
"missing.xlsx".to_string(),
context
);
// 解析错误
let error = DocumentError::parse_error_with_context(
"worksheet".to_string(),
context
);
// Excel错误
let error = DocumentError::xlsx_error_with_context(
"Sheet1".to_string(),
context
);
```
## 📈 性能考虑
- 错误监控使用原子操作和互斥锁,性能开销很小
- 错误上下文信息是可选的,不会影响正常处理流程
- 错误统计信息存储在内存中,可以定期清理
## 🎯 示例代码
完整的使用示例请参考:
- `examples/error_handling_example.rs` - 基础错误处理示例
- `examples/advanced_error_handling.rs` - 高级错误处理示例
运行示例:
```bash
cargo run --example advanced_error_handling
```
## 🔄 迁移指南
如果你正在从旧版本的错误处理系统迁移:
1. **基本错误处理保持不变**:现有的错误处理代码无需修改
2. **新增功能是可选的**:可以逐步采用新的错误处理功能
3. **向后兼容**:所有现有的错误类型和方法都保持兼容
## 📝 总结
新的错误处理系统提供了:
✅ **更好的调试体验** - 详细的错误上下文信息
✅ **智能错误恢复** - 自动提供恢复建议
✅ **程序化错误处理** - 结构化的错误码系统
✅ **错误监控和分析** - 自动收集错误统计
✅ **向后兼容** - 不破坏现有代码
✅ **高性能** - 最小的性能开销
这些功能大大提升了库的可用性、可维护性和用户体验。