Skip to main content

csv_cat/
error.rs

1//! Project-wide error type.
2
3/// All errors in csv-cat.
4#[derive(Debug)]
5pub enum CsvError {
6    /// Underlying csv crate error.
7    Csv(csv::Error),
8    /// IO error.
9    Io(std::io::Error),
10    /// A field was missing or could not be accessed.
11    MissingField { index: usize },
12    /// Deserialization of a typed record failed.
13    Deserialize(String),
14}
15
16impl std::fmt::Display for CsvError {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        match self {
19            Self::Csv(e) => write!(f, "CSV error: {e}"),
20            Self::Io(e) => write!(f, "IO error: {e}"),
21            Self::MissingField { index } => write!(f, "missing field at index {index}"),
22            Self::Deserialize(msg) => write!(f, "deserialization error: {msg}"),
23        }
24    }
25}
26
27impl std::error::Error for CsvError {
28    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
29        match self {
30            Self::Csv(e) => Some(e),
31            Self::Io(e) => Some(e),
32            Self::MissingField { .. } | Self::Deserialize(_) => None,
33        }
34    }
35}
36
37impl From<csv::Error> for CsvError {
38    fn from(e: csv::Error) -> Self { Self::Csv(e) }
39}
40
41impl From<std::io::Error> for CsvError {
42    fn from(e: std::io::Error) -> Self { Self::Io(e) }
43}