Skip to main content

fast_excel/
error.rs

1//! 工具内部统一错误类型
2//!
3//! 设计原则:库内部不依赖 Web 层,所有错误先收敛成 [`ExcelError`]。
4//! 业务侧需要时再自行实现 `From<ExcelError> for AppError` 等映射
5//! ([`ExcelError::code`] 给出 `excel_xxx` key,可拼成 `@excel_xxx` 消息便于前端 i18n)。
6
7use std::fmt;
8
9/// Excel 工具错误
10#[derive(Debug, Clone)]
11pub enum ExcelError {
12    /// 文件 / IO 错误
13    Io(String),
14    /// xlsx 容器(zip)错误
15    Zip(String),
16    /// XML 解析错误
17    Xml(String),
18    /// 不是合法的 xlsx 文件
19    NotXlsx(String),
20    /// 找不到指定工作表
21    SheetNotFound(String),
22    /// 表头缺少必填列(动态表头适配失败)
23    MissingColumns(Vec<String>),
24    /// 单元格级错误
25    InvalidCell {
26        row: u32,
27        column: String,
28        message: String,
29    },
30    /// 行级错误(同一行多列错误)
31    InvalidRow { row: u32, messages: Vec<String> },
32    /// 不支持的能力(例如加密 xlsx、非 deflate 压缩)
33    Unsupported(String),
34    /// 批量落库失败
35    Sink(String),
36    /// 其它
37    Other(String),
38}
39
40impl ExcelError {
41    /// 错误码(前端 i18n key 后缀,与项目 `@xxx` 消息约定一致)
42    pub fn code(&self) -> &'static str {
43        match self {
44            ExcelError::Io(_) => "excel_io_failed",
45            ExcelError::Zip(_) => "excel_zip_failed",
46            ExcelError::Xml(_) => "excel_xml_failed",
47            ExcelError::NotXlsx(_) => "excel_not_xlsx",
48            ExcelError::SheetNotFound(_) => "excel_sheet_not_found",
49            ExcelError::MissingColumns(_) => "excel_missing_column",
50            ExcelError::InvalidCell { .. } => "excel_invalid_cell",
51            ExcelError::InvalidRow { .. } => "excel_invalid_row",
52            ExcelError::Unsupported(_) => "excel_unsupported",
53            ExcelError::Sink(_) => "excel_sink_failed",
54            ExcelError::Other(_) => "excel_error",
55        }
56    }
57
58    pub fn other(msg: impl Into<String>) -> Self {
59        ExcelError::Other(msg.into())
60    }
61
62    pub fn unsupported(msg: impl Into<String>) -> Self {
63        ExcelError::Unsupported(msg.into())
64    }
65}
66
67impl fmt::Display for ExcelError {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        match self {
70            ExcelError::Io(m) => write!(f, "文件读写失败:{m}"),
71            ExcelError::Zip(m) => write!(f, "Excel 文件损坏或格式不支持:{m}"),
72            ExcelError::Xml(m) => write!(f, "Excel 内部结构解析失败:{m}"),
73            ExcelError::NotXlsx(m) => write!(f, "不是有效的 xlsx 文件:{m}"),
74            ExcelError::SheetNotFound(m) => write!(f, "工作表不存在:{m}"),
75            ExcelError::MissingColumns(cols) => write!(f, "缺少必填列:{}", cols.join("、")),
76            ExcelError::InvalidCell {
77                row,
78                column,
79                message,
80            } => {
81                write!(f, "第 {row} 行「{column}」列:{message}")
82            }
83            ExcelError::InvalidRow { row, messages } => {
84                write!(f, "第 {row} 行:{}", messages.join(";"))
85            }
86            ExcelError::Unsupported(m) => write!(f, "暂不支持的 Excel 特性:{m}"),
87            ExcelError::Sink(m) => write!(f, "数据写入失败:{m}"),
88            ExcelError::Other(m) => write!(f, "{m}"),
89        }
90    }
91}
92
93impl std::error::Error for ExcelError {}
94
95impl From<std::io::Error> for ExcelError {
96    fn from(e: std::io::Error) -> Self {
97        ExcelError::Io(e.to_string())
98    }
99}
100
101impl From<zip::result::ZipError> for ExcelError {
102    fn from(e: zip::result::ZipError) -> Self {
103        ExcelError::Zip(e.to_string())
104    }
105}
106
107impl From<quick_xml::Error> for ExcelError {
108    fn from(e: quick_xml::Error) -> Self {
109        ExcelError::Xml(e.to_string())
110    }
111}
112
113impl From<rust_xlsxwriter::XlsxError> for ExcelError {
114    fn from(e: rust_xlsxwriter::XlsxError) -> Self {
115        ExcelError::Other(format!("Excel 生成失败:{e}"))
116    }
117}
118
119impl From<serde_json::Error> for ExcelError {
120    fn from(e: serde_json::Error) -> Self {
121        ExcelError::Other(format!("JSON 序列化失败:{e}"))
122    }
123}
124
125impl From<chrono::ParseError> for ExcelError {
126    fn from(e: chrono::ParseError) -> Self {
127        ExcelError::Other(format!("日期解析失败:{e}"))
128    }
129}
130
131/// 便捷别名
132pub type Result<T> = std::result::Result<T, ExcelError>;