Skip to main content

excel_rs/
error.rs

1use std::fmt;
2
3#[derive(Debug)]
4pub enum ExcelError {
5    /// An IO error occurred while writing to an underlying writer.
6    Io(std::io::Error),
7    /// An error occurred zipping the excel file.
8    Zip(zip::result::ZipError),
9    /// Attempted to create more sheets than the maximum allowed (65535).
10    TooManySheets,
11    /// Attempted to write more rows than Excel supports (1048576).
12    RowLimitExceeded,
13    /// Attempted to write more columns than Excel supports (16384).
14    ColumnLimitExceeded,
15    /// Attempted to write header after already writing rows.
16    HeaderAfterRows,
17    /// Attempted to create a sheet that already exists.
18    SheetAlreadyExists,
19}
20
21pub type Result<T> = std::result::Result<T, ExcelError>;
22
23impl fmt::Display for ExcelError {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        match self {
26            Self::Io(e) => write!(f, "IO error: {e}"),
27            Self::Zip(e) => write!(f, "ZIP error: {e}"),
28            Self::TooManySheets => {
29                write!(f, "exceeded maximum sheet count of {}", u16::MAX)
30            }
31            Self::RowLimitExceeded => {
32                write!(f, "exceeded Excel row limit of {}", 1048576)
33            }
34            Self::ColumnLimitExceeded => {
35                write!(f, "exceeded Excel column limit of {}", 16384)
36            }
37            Self::HeaderAfterRows => {
38                write!(f, "you cannot write a header after already writing rows")
39            }
40            Self::SheetAlreadyExists => {
41                write!(f, "a sheet with that name already exists. sheets need to have unique names")
42            }
43        }
44    }
45}
46
47impl std::error::Error for ExcelError {
48    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
49        match self {
50            Self::Io(e) => Some(e),
51            Self::Zip(e) => Some(e),
52            _ => None,
53        }
54    }
55}
56
57impl From<std::io::Error> for ExcelError {
58    fn from(e: std::io::Error) -> Self {
59        Self::Io(e)
60    }
61}
62
63impl From<zip::result::ZipError> for ExcelError {
64    fn from(e: zip::result::ZipError) -> Self {
65        Self::Zip(e)
66    }
67}