Skip to main content

openreadout_core/
error.rs

1//! Error type and the exit-code contract.
2//!
3//! Exit codes are part of the public interface (agents branch on them):
4//! 0 ok · 1 error · 2 usage · 3 unknown/unsupported format · 4 corrupt or truncated ·
5//! 5 I/O · 6 known format but unsupported feature.
6
7use std::path::PathBuf;
8
9/// What to do about a usage error, from the kind of mistake its message describes.
10fn usage_hint(message: &str) -> &'static str {
11    let m = message.to_ascii_lowercase();
12    if m.contains("the output name `") {
13        "Name the output with the extension of the format you want (.ome.tiff, .ome.zarr, .mzML, .csv, .parquet, .arrow, .nwb, .jdx, .asm.json, .rdml), or set the format explicitly."
14    } else if m.contains("--overwrite") {
15        "Choose another output path, or pass --overwrite to replace that file (the input is never modified)."
16    } else if m.contains(crate::output::OUTPUT_IS_INPUT) {
17        "Choose an output path that is not one of the input files; OpenReadout writes new files next to the raw data and never replaces it."
18    } else if m.contains("out of range: use") {
19        "Use a value inside the range the message gives."
20    } else if m.contains("select") {
21        "Selections are zero-based and repeatable: `c=0`, `z=1-3`, `t=0,2`; `openreadout info FILE --json` gives each image's size_c, size_z and size_t."
22    } else if [
23        "out of range",
24        "does not exist",
25        "past the end",
26        "no such",
27        "not found",
28    ]
29    .iter()
30    .any(|k| m.contains(k))
31    {
32        "Indices are zero-based; `openreadout info FILE --json` lists the images, traces (sweep_count, sample_count), tables (row_count) and spectra the file holds."
33    } else {
34        "Check the arguments with `openreadout help <command>`; `openreadout info FILE --json` shows what the file holds."
35    }
36}
37
38/// What to do about an unexpected failure.
39fn other_hint(message: &str) -> &'static str {
40    let m = message.to_ascii_lowercase();
41    if m.contains("read-back") || m.contains("read back") || m.contains("verif") {
42        "The output was written to a temporary file that failed verification, so nothing was kept; check free disk space and the output directory, then rerun."
43    } else {
44        "Unexpected failure: rerun with --json for the full error, and report it with `openreadout --version` and `openreadout info FILE --json`."
45    }
46}
47
48/// Added to the message when a reader matched only the file's extension and could not open it.
49pub(crate) const EXTENSION_ONLY: &str = "only the file extension matched this format";
50
51/// The hint for such a failure.
52pub(crate) const EXTENSION_ONLY_HINT: &str = "The file's first bytes do not look like this format, only its extension does: it may be another kind of file with the same extension, or damaged from the start. `openreadout info --view format FILE` shows what was detected.";
53
54/// Readers put this phrase in the message when a file that a multi-file data set lists is not
55/// there (an OME-TIFF member, an NDPI set's NDPI, a MetaMorph `.nd` file).
56pub const MISSING_MEMBER: &str = "of the data set is missing";
57
58/// The hint for such a failure.
59pub(crate) const MISSING_MEMBER_HINT: &str = "A file this data set lists is not next to the file you opened. Copy the whole data set (the file you opened and every file it names) into one folder, keeping the names; `openreadout check FILE` lists what is missing.";
60
61/// Result alias used throughout `OpenReadout`.
62pub type Result<T> = std::result::Result<T, Error>;
63
64/// Every failure `OpenReadout` can report. Each variant maps to a stable string code
65/// (for JSON) and an exit code (for shells).
66#[derive(Debug, thiserror::Error)]
67#[non_exhaustive]
68pub enum Error {
69    /// The file does not match any supported format's signature.
70    #[error("unrecognized file format: {path}")]
71    UnknownFormat {
72        /// The file that was not recognised.
73        path: PathBuf,
74    },
75
76    /// The format is known but this file uses a feature we do not decode yet.
77    #[error("{format}: unsupported feature: {feature}")]
78    Unsupported {
79        /// Format id (or command) that reported it.
80        format: &'static str,
81        /// What is not supported.
82        feature: String,
83        /// What the caller can do instead.
84        hint: Option<String>,
85    },
86
87    /// The file violates its own format's invariants (truncation, bad offsets, ...).
88    #[error("{format}: corrupt file: {detail}")]
89    Corrupt {
90        /// Format id that reported it.
91        format: &'static str,
92        /// What is wrong.
93        detail: String,
94        /// Byte offset of the problem, when known.
95        offset: Option<u64>,
96    },
97
98    /// Bad arguments or an impossible request (e.g. plane index out of range).
99    #[error("usage error: {0}")]
100    Usage(String),
101
102    /// Operating-system I/O failure.
103    #[error("I/O error on {path}: {source}")]
104    Io {
105        /// The file or directory involved.
106        path: PathBuf,
107        /// The operating-system error.
108        #[source]
109        source: std::io::Error,
110    },
111
112    /// Anything else.
113    #[error("{0}")]
114    Other(String),
115}
116
117impl Error {
118    /// Stable machine-readable code for the JSON envelope.
119    pub fn code(&self) -> &'static str {
120        match self {
121            Error::UnknownFormat { .. } => "unknown_format",
122            Error::Unsupported { .. } => "unsupported_feature",
123            Error::Corrupt { .. } => "corrupt_file",
124            Error::Usage(_) => "usage",
125            Error::Io { .. } => "io",
126            Error::Other(_) => "error",
127        }
128    }
129
130    /// Process exit code for this error.
131    pub fn exit_code(&self) -> i32 {
132        match self {
133            Error::Other(_) => 1,
134            Error::Usage(_) => 2,
135            Error::UnknownFormat { .. } => 3,
136            Error::Corrupt { .. } => 4,
137            Error::Io { .. } => 5,
138            Error::Unsupported { .. } => 6,
139        }
140    }
141
142    /// A suggestion the caller (human or agent) can act on.
143    pub fn hint(&self) -> Option<String> {
144        match self {
145            Error::UnknownFormat { path } if path.is_dir() => Some(
146                "This folder is not a data set that one reader opens as a whole: name a file in it, or use `openreadout batch` to read every file of the folder.".into(),
147            ),
148            Error::UnknownFormat { path } => {
149                let name = path.file_name().map(|n| n.to_string_lossy());
150                Some(match name.as_deref().and_then(|n| n.strip_prefix("._")) {
151                    Some(data) if !data.is_empty() => format!(
152                        "This is a macOS AppleDouble file: Finder metadata that macOS writes next to `{data}`, not data. Open `{data}` instead, and skip `._*` files."
153                    ),
154                    _ => "No reader recognised the file's first bytes, so a matching extension alone is not enough: the file may be another kind of file with the same extension, a format not yet implemented, or a renamed export. `openreadout self formats` lists the supported formats.".into(),
155                })
156            }
157            Error::Unsupported { hint, .. } => hint.clone(),
158            Error::Corrupt { detail, .. } if detail.contains(EXTENSION_ONLY) => {
159                Some(EXTENSION_ONLY_HINT.into())
160            }
161            Error::Corrupt { detail, .. } if detail.contains(MISSING_MEMBER) => {
162                Some(MISSING_MEMBER_HINT.into())
163            }
164            Error::Corrupt { .. } => Some(
165                "Run `openreadout check <file>` for a full integrity report. The file may be truncated by an interrupted acquisition or copy."
166                    .into(),
167            ),
168            Error::Io { source, .. } if source.kind() == std::io::ErrorKind::IsADirectory => Some(
169                "This is a folder and the command takes one file: name a file in it, or use `openreadout batch` to read every file of the folder.".into(),
170            ),
171            Error::Io { .. } => Some("Check that the path exists and is readable.".into()),
172            Error::Usage(m) => Some(usage_hint(m).into()),
173            Error::Other(m) => Some(other_hint(m).into()),
174        }
175    }
176
177    /// Convenience constructor for I/O errors carrying the path.
178    pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
179        Error::Io {
180            path: path.into(),
181            source,
182        }
183    }
184
185    /// Convenience constructor for corruption findings.
186    pub fn corrupt(format: &'static str, detail: impl Into<String>) -> Self {
187        Error::Corrupt {
188            format,
189            detail: detail.into(),
190            offset: None,
191        }
192    }
193
194    /// Convenience constructor for corruption findings at a known byte offset.
195    pub fn corrupt_at(format: &'static str, offset: u64, detail: impl Into<String>) -> Self {
196        Error::Corrupt {
197            format,
198            detail: detail.into(),
199            offset: Some(offset),
200        }
201    }
202
203    /// Convenience constructor for unsupported features.
204    pub fn unsupported(
205        format: &'static str,
206        feature: impl Into<String>,
207        hint: impl Into<String>,
208    ) -> Self {
209        Error::Unsupported {
210            format,
211            feature: feature.into(),
212            hint: Some(hint.into()),
213        }
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    /// Every error an agent can hit carries a hint it can act on.
222    #[test]
223    fn every_error_has_a_hint() {
224        let errors = [
225            Error::UnknownFormat { path: "x".into() },
226            Error::unsupported("x", "y", "Convert it first."),
227            Error::corrupt("x", "y"),
228            Error::Usage("sweep 9 out of range (trace 0 has 3 sweeps, 0..3)".into()),
229            Error::Usage("out.csv exists; pass --overwrite to replace it".into()),
230            Error::Usage("selection matches no planes".into()),
231            Error::Usage("anything".into()),
232            Error::io("x", std::io::Error::other("y")),
233            Error::Other("Parquet read-back: bad".into()),
234            Error::Other("anything".into()),
235            Error::corrupt(
236                "tiff",
237                format!("file 'a.ndpi' {MISSING_MEMBER} (looked for a.ndpi)"),
238            ),
239        ];
240        for e in &errors {
241            assert!(e.hint().is_some_and(|h| h.len() > 10), "{e}");
242        }
243        let hint = |i: usize| errors[i].hint().unwrap_or_default();
244        assert!(hint(3).contains("info FILE --json"));
245        assert!(hint(4).contains("--overwrite"));
246        assert!(hint(5).contains("c=0"));
247        assert!(hint(8).contains("verification"));
248        assert!(hint(10).contains("whole data set"));
249    }
250
251    /// A value out of its range is not an index: its hint does not talk about indices. An
252    /// output that is an input gets its own hint.
253    #[test]
254    fn value_ranges_and_inputs_get_their_own_hints() {
255        let hint = |m: &str| Error::Usage(m.into()).hint().unwrap_or_default();
256        let h = hint("dpi 5 is out of range: use 36 to 2400 (300 is usual for print)");
257        assert!(!h.contains("zero-based"), "{h}");
258        assert!(hint("scale 9 is out of range: use 0.25 to 8").contains("range the message gives"));
259        assert!(
260            hint("output a.tif is the input file a.tif; raw files are never modified")
261                .contains("not one of the input files")
262        );
263        assert!(hint("image index 4 out of range (0..2)").contains("zero-based"));
264    }
265}