Skip to main content

deepdoc_core/
error.rs

1//! Core error type. The CLI maps these onto the exit codes from the spec.
2
3use std::path::{Path, PathBuf};
4
5use crate::detect::Format;
6
7pub type Result<T> = std::result::Result<T, Error>;
8
9/// Process exit codes (see `docs/PRD/02-cli-spec.md`).
10pub mod exit_code {
11    /// Success.
12    pub const OK: i32 = 0;
13    /// Generic failure.
14    pub const FAILURE: i32 = 1;
15    /// Invalid arguments (also what clap returns on its own).
16    pub const USAGE: i32 = 2;
17    /// Recognised document, but no extractable text — looks like a scan, needs `--ocr`.
18    pub const NO_TEXT: i32 = 4;
19    /// Unsupported file type.
20    pub const UNSUPPORTED: i32 = 5;
21}
22
23#[derive(Debug, thiserror::Error)]
24pub enum Error {
25    #[error("cannot read {path}: {source}")]
26    Io {
27        path: PathBuf,
28        #[source]
29        source: std::io::Error,
30    },
31
32    #[error("unsupported file type: {path}")]
33    Unsupported { path: PathBuf },
34
35    /// The type is known but its extractor has not landed yet (pre-v0.1 only).
36    #[error("{format} is not supported yet")]
37    NotImplemented { format: Format },
38
39    #[error("{path} has no extractable text — it looks like a scan (needs --ocr)")]
40    NoText { path: PathBuf },
41
42    #[error("cannot parse {path}: {message}")]
43    Parse { path: PathBuf, message: String },
44
45    #[error("invalid page range {input:?}: {message}")]
46    InvalidPageRange { input: String, message: String },
47}
48
49impl Error {
50    /// Read error carrying the path that failed.
51    pub fn io(path: impl AsRef<Path>, source: std::io::Error) -> Self {
52        Error::Io {
53            path: path.as_ref().to_path_buf(),
54            source,
55        }
56    }
57
58    pub fn parse(path: impl AsRef<Path>, message: impl Into<String>) -> Self {
59        Error::Parse {
60            path: path.as_ref().to_path_buf(),
61            message: message.into(),
62        }
63    }
64
65    /// The exit code this error should produce.
66    pub fn exit_code(&self) -> i32 {
67        match self {
68            Error::Unsupported { .. } | Error::NotImplemented { .. } => exit_code::UNSUPPORTED,
69            Error::NoText { .. } => exit_code::NO_TEXT,
70            Error::InvalidPageRange { .. } => exit_code::USAGE,
71            Error::Io { .. } | Error::Parse { .. } => exit_code::FAILURE,
72        }
73    }
74}