Skip to main content

sheetkit_core/
error.rs

1//! Error types for the SheetKit core library.
2//!
3//! Provides a comprehensive [`Error`](enum@Error) enum covering all failure modes
4//! encountered when reading, writing, and manipulating Excel workbooks.
5
6use thiserror::Error;
7
8use crate::resource::{ResourceCategory, ResourceLimitError};
9
10/// The top-level error type for SheetKit.
11#[derive(Error, Debug)]
12pub enum Error {
13    /// A finite resource budget was exhausted.
14    #[error("{0}")]
15    ResourceLimitExceeded(#[from] ResourceLimitError),
16
17    /// The given string is not a valid A1-style cell reference.
18    #[error("invalid cell reference: {0}")]
19    InvalidCellReference(String),
20
21    /// The row number is out of the allowed range (1..=1_048_576).
22    #[error("invalid row number: {0}")]
23    InvalidRowNumber(u32),
24
25    /// The column number is out of the allowed range (1..=16_384).
26    #[error("invalid column number: {0}")]
27    InvalidColumnNumber(u32),
28
29    /// No sheet with the given name exists in the workbook.
30    #[error("sheet '{name}' does not exist")]
31    SheetNotFound { name: String },
32
33    /// A sheet with the given name already exists.
34    #[error("sheet '{name}' already exists")]
35    SheetAlreadyExists { name: String },
36
37    /// The sheet name violates Excel naming rules.
38    #[error("invalid sheet name: {0}")]
39    InvalidSheetName(String),
40
41    /// An underlying I/O error.
42    #[error("I/O error: {0}")]
43    Io(#[from] std::io::Error),
44
45    /// An error originating from the ZIP layer.
46    #[error("ZIP error: {0}")]
47    Zip(String),
48
49    /// An error encountered while parsing XML.
50    #[error("XML parse error: {0}")]
51    XmlParse(String),
52
53    /// An error encountered while deserializing XML into typed structures.
54    #[error("XML deserialization error: {0}")]
55    XmlDeserialize(String),
56
57    /// Column width exceeds the allowed maximum (255).
58    #[error("column width {width} exceeds maximum {max}")]
59    ColumnWidthExceeded { width: f64, max: f64 },
60
61    /// Row height exceeds the allowed maximum (409).
62    #[error("row height {height} exceeds maximum {max}")]
63    RowHeightExceeded { height: f64, max: f64 },
64
65    /// A cell value exceeds the maximum character limit.
66    #[error("cell value too long: {length} characters (max {max})")]
67    CellValueTooLong { length: usize, max: usize },
68
69    /// The style ID was not found in the stylesheet.
70    #[error("style not found: {id}")]
71    StyleNotFound { id: u32 },
72
73    /// Too many cell styles have been registered.
74    #[error("cell styles exceeded maximum ({max})")]
75    CellStylesExceeded { max: usize },
76
77    /// A row has already been written; rows must be written in ascending order.
78    #[error("row {row} has already been written (must write rows in ascending order)")]
79    StreamRowAlreadyWritten { row: u32 },
80
81    /// The stream writer has already been finished.
82    #[error("stream writer already finished")]
83    StreamAlreadyFinished,
84
85    /// A random-access mutation would discard a streamed sheet's row data.
86    #[error("cannot mutate streamed sheet '{sheet}' with random-access operations")]
87    StreamedSheetMutation { sheet: String },
88
89    /// A streamed numeric or date value is not finite.
90    #[error("streamed numeric values must be finite")]
91    StreamNonFiniteValue,
92
93    /// Column widths cannot be set after rows have been written.
94    #[error("cannot set column width after rows have been written")]
95    StreamColumnsAfterRows,
96
97    /// Merge cell ranges overlap.
98    #[error("merge cell range '{new}' overlaps with existing range '{existing}'")]
99    MergeCellOverlap { new: String, existing: String },
100
101    /// The specified merge cell range was not found.
102    #[error("merge cell range '{0}' not found")]
103    MergeCellNotFound(String),
104
105    /// The defined name is invalid.
106    #[error("invalid defined name: {0}")]
107    InvalidDefinedName(String),
108
109    /// The specified defined name was not found.
110    #[error("defined name '{name}' not found")]
111    DefinedNameNotFound { name: String },
112
113    /// A circular reference was detected during formula evaluation.
114    #[error("circular reference detected at {cell}")]
115    CircularReference { cell: String },
116
117    /// The formula references an unknown function.
118    #[error("unknown function: {name}")]
119    UnknownFunction { name: String },
120
121    /// A function received the wrong number of arguments.
122    #[error("function {name} expects {expected} arguments, got {got}")]
123    WrongArgCount {
124        name: String,
125        expected: String,
126        got: usize,
127    },
128
129    /// A general formula evaluation error.
130    #[error("formula evaluation error: {0}")]
131    FormulaError(String),
132
133    /// The specified pivot table was not found.
134    #[error("pivot table '{name}' not found")]
135    PivotTableNotFound { name: String },
136
137    /// A pivot table with the given name already exists.
138    #[error("pivot table '{name}' already exists")]
139    PivotTableAlreadyExists { name: String },
140
141    /// The specified table was not found.
142    #[error("table '{name}' not found")]
143    TableNotFound { name: String },
144
145    /// A table with the given name already exists.
146    #[error("table '{name}' already exists")]
147    TableAlreadyExists { name: String },
148
149    /// The source data range for a pivot table is invalid.
150    #[error("invalid source range: {0}")]
151    InvalidSourceRange(String),
152
153    /// The specified slicer was not found.
154    #[error("slicer '{name}' not found")]
155    SlicerNotFound { name: String },
156
157    /// A slicer with the given name already exists.
158    #[error("slicer '{name}' already exists")]
159    SlicerAlreadyExists { name: String },
160
161    /// The specified column was not found in the table.
162    #[error("column '{column}' not found in table '{table}'")]
163    TableColumnNotFound { table: String, column: String },
164
165    /// The image format is not supported.
166    #[error("unsupported image format: {format}")]
167    UnsupportedImageFormat { format: String },
168
169    /// The file is encrypted and requires a password to open.
170    #[error("file is encrypted, password required")]
171    FileEncrypted,
172
173    /// The provided password is incorrect.
174    #[error("incorrect password")]
175    IncorrectPassword,
176
177    /// The encryption method is not supported.
178    #[error("unsupported encryption method: {0}")]
179    UnsupportedEncryption(String),
180
181    /// The outline level exceeds the allowed maximum (7).
182    #[error("outline level {level} exceeds maximum {max}")]
183    OutlineLevelExceeded { level: u8, max: u8 },
184
185    /// A merge cell reference format is invalid.
186    #[error("invalid merge cell reference: {0}")]
187    InvalidMergeCellReference(String),
188
189    /// A cell range reference (sqref) is invalid.
190    #[error("invalid reference: {reference}")]
191    InvalidReference { reference: String },
192
193    /// A function argument or configuration value is invalid.
194    #[error("invalid argument: {0}")]
195    InvalidArgument(String),
196
197    /// The file extension is not a supported OOXML spreadsheet format.
198    #[error("unsupported file extension: {0}")]
199    UnsupportedFileExtension(String),
200
201    /// The specified threaded comment was not found.
202    #[error("threaded comment '{id}' not found")]
203    ThreadedCommentNotFound { id: String },
204
205    /// No chart was found at the specified cell.
206    #[error("no chart found at cell '{cell}' on sheet '{sheet}'")]
207    ChartNotFound { sheet: String, cell: String },
208
209    /// No picture was found at the specified cell.
210    #[error("no picture found at cell '{cell}' on sheet '{sheet}'")]
211    PictureNotFound { sheet: String, cell: String },
212
213    /// An internal or otherwise unclassified error.
214    #[error("internal error: {0}")]
215    Internal(String),
216}
217
218impl Error {
219    /// Returns a stable machine-readable error code.
220    pub const fn code(&self) -> &'static str {
221        match self {
222            Self::ResourceLimitExceeded(_) => ResourceLimitError::CODE,
223            _ => "sheetkit_error",
224        }
225    }
226
227    /// Returns structured resource metadata when this is a budget error.
228    pub const fn resource_metadata(&self) -> Option<&ResourceLimitError> {
229        match self {
230            Self::ResourceLimitExceeded(metadata) => Some(metadata),
231            _ => None,
232        }
233    }
234
235    /// Returns the closed resource category when this is a budget error.
236    pub const fn resource_category(&self) -> Option<ResourceCategory> {
237        match self.resource_metadata() {
238            Some(metadata) => Some(metadata.category()),
239            None => None,
240        }
241    }
242}
243
244/// A convenience alias used throughout the crate.
245pub type Result<T> = std::result::Result<T, Error>;
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    #[test]
252    fn resource_limit_metadata_rejects_non_exhaustion() {
253        assert!(crate::resource::ResourceLimitError::exceeded(
254            crate::resource::ResourceOperation::WorkbookOpen,
255            crate::resource::ResourceCategory::Archive,
256            crate::resource::ResourceDimension::EntryCount,
257            10,
258            10,
259            Some(crate::resource::ResourceStage::Inspect),
260        )
261        .is_none());
262    }
263
264    #[test]
265    fn resource_limit_error_has_stable_bounded_output() {
266        let metadata = crate::resource::ResourceLimitError::exceeded(
267            crate::resource::ResourceOperation::WorkbookOpen,
268            crate::resource::ResourceCategory::Archive,
269            crate::resource::ResourceDimension::EntryCount,
270            10,
271            11,
272            Some(crate::resource::ResourceStage::Inspect),
273        )
274        .unwrap();
275        let error = Error::from(metadata);
276
277        assert_eq!(error.code(), "resource_limit_exceeded");
278        assert_eq!(
279            error.to_string(),
280            "resource limit exceeded: operation=workbook_open category=archive \
281             dimension=entry_count limit=10 observed=11 stage=inspect"
282        );
283    }
284
285    #[test]
286    fn test_error_display_invalid_cell_reference() {
287        let err = Error::InvalidCellReference("XYZ0".to_string());
288        assert_eq!(err.to_string(), "invalid cell reference: XYZ0");
289    }
290
291    #[test]
292    fn test_error_display_sheet_not_found() {
293        let err = Error::SheetNotFound {
294            name: "Missing".to_string(),
295        };
296        assert_eq!(err.to_string(), "sheet 'Missing' does not exist");
297    }
298
299    #[test]
300    fn test_error_display_sheet_already_exists() {
301        let err = Error::SheetAlreadyExists {
302            name: "Sheet1".to_string(),
303        };
304        assert_eq!(err.to_string(), "sheet 'Sheet1' already exists");
305    }
306
307    #[test]
308    fn test_error_display_invalid_sheet_name() {
309        let err = Error::InvalidSheetName("bad[name".to_string());
310        assert_eq!(err.to_string(), "invalid sheet name: bad[name");
311    }
312
313    #[test]
314    fn test_error_display_invalid_row_number() {
315        let err = Error::InvalidRowNumber(0);
316        assert_eq!(err.to_string(), "invalid row number: 0");
317    }
318
319    #[test]
320    fn test_error_display_invalid_column_number() {
321        let err = Error::InvalidColumnNumber(99999);
322        assert_eq!(err.to_string(), "invalid column number: 99999");
323    }
324
325    #[test]
326    fn test_error_display_io() {
327        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
328        let err = Error::Io(io_err);
329        assert_eq!(err.to_string(), "I/O error: gone");
330    }
331
332    #[test]
333    fn test_error_display_zip() {
334        let err = Error::Zip("corrupted archive".to_string());
335        assert_eq!(err.to_string(), "ZIP error: corrupted archive");
336    }
337
338    #[test]
339    fn test_error_display_xml_parse() {
340        let err = Error::XmlParse("unexpected EOF".to_string());
341        assert_eq!(err.to_string(), "XML parse error: unexpected EOF");
342    }
343
344    #[test]
345    fn test_error_display_xml_deserialize() {
346        let err = Error::XmlDeserialize("missing attribute".to_string());
347        assert_eq!(
348            err.to_string(),
349            "XML deserialization error: missing attribute"
350        );
351    }
352
353    #[test]
354    fn test_error_display_cell_value_too_long() {
355        let err = Error::CellValueTooLong {
356            length: 40000,
357            max: 32767,
358        };
359        assert_eq!(
360            err.to_string(),
361            "cell value too long: 40000 characters (max 32767)"
362        );
363    }
364
365    #[test]
366    fn test_error_display_outline_level_exceeded() {
367        let err = Error::OutlineLevelExceeded { level: 8, max: 7 };
368        assert_eq!(err.to_string(), "outline level 8 exceeds maximum 7");
369    }
370
371    #[test]
372    fn test_error_display_invalid_merge_cell_reference() {
373        let err = Error::InvalidMergeCellReference("bad ref".to_string());
374        assert_eq!(err.to_string(), "invalid merge cell reference: bad ref");
375    }
376
377    #[test]
378    fn test_error_display_unsupported_file_extension() {
379        let err = Error::UnsupportedFileExtension("csv".to_string());
380        assert_eq!(err.to_string(), "unsupported file extension: csv");
381    }
382
383    #[test]
384    fn test_error_display_internal() {
385        let err = Error::Internal("something went wrong".to_string());
386        assert_eq!(err.to_string(), "internal error: something went wrong");
387    }
388
389    #[test]
390    fn test_from_io_error() {
391        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
392        let err: Error = io_err.into();
393        assert!(matches!(err, Error::Io(_)));
394    }
395
396    #[test]
397    fn test_error_is_send_and_sync() {
398        fn assert_send<T: Send>() {}
399        fn assert_sync<T: Sync>() {}
400        assert_send::<Error>();
401        assert_sync::<Error>();
402    }
403}