Skip to main content

c4/
error.rs

1//! The crate error type: everything scanning, parsing, merging or
2//! deserializing can fail with.
3
4use std::path::PathBuf;
5
6pub type Result<T> = std::result::Result<T, Error>;
7
8/// Errors produced while scanning, parsing, merging or deserializing.
9///
10/// Non-exhaustive: new variants may come without a breaking release, so
11/// a `match` needs a `_` arm.
12#[derive(Debug)]
13#[non_exhaustive]
14pub enum Error {
15    /// Reading `path` (a file, or a folder while scanning) failed.
16    Io {
17        path: PathBuf,
18        source: std::io::Error,
19    },
20    /// A source path does not exist.
21    NotFound(PathBuf),
22    /// A file failed to parse.
23    Parse { path: PathBuf, message: String },
24    /// A table row failed to convert (csv, a spreadsheet sheet, or rows
25    /// handed to [`parse_table`](crate::parse_table)). `row` is 1-based —
26    /// for a sheet, the real spreadsheet row number.
27    Table {
28        path: PathBuf,
29        row: usize,
30        message: String,
31    },
32    /// The merged value could not deserialize into the requested type.
33    Deserialize(String),
34    /// An option requires a Cargo feature that is not compiled in.
35    Unsupported(String),
36}
37
38impl std::fmt::Display for Error {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        match self {
41            Error::Io { path, source } => write!(f, "{}: {source}", path.display()),
42            Error::NotFound(p) => write!(f, "source not found: {}", p.display()),
43            Error::Parse { path, message } => write!(f, "{}: {message}", path.display()),
44            Error::Table { path, row, message } => {
45                write!(f, "{} row {row}: {message}", path.display())
46            }
47            Error::Deserialize(m) => write!(f, "deserialize error: {m}"),
48            Error::Unsupported(m) => write!(f, "unsupported: {m}"),
49        }
50    }
51}
52
53impl std::error::Error for Error {
54    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
55        match self {
56            Error::Io { source, .. } => Some(source),
57            _ => None,
58        }
59    }
60}
61
62/// The `map_err` adapter for an I/O call on `path`.
63pub(crate) fn io(path: &std::path::Path) -> impl FnOnce(std::io::Error) -> Error + '_ {
64    move |source| Error::Io {
65        path: path.to_path_buf(),
66        source,
67    }
68}