Skip to main content

contract_cli/
error.rs

1use thiserror::Error;
2
3#[derive(Error, Debug)]
4pub enum AppError {
5    #[error("Invalid input: {0}")]
6    InvalidInput(String),
7
8    #[error("Config error: {0}")]
9    Config(String),
10
11    #[error("Not found: {0}")]
12    NotFound(String),
13
14    #[error("Ambiguous: {0}")]
15    Ambiguous(String),
16
17    #[error("IO error: {0}")]
18    Io(#[from] std::io::Error),
19
20    #[error("Database error: {0}")]
21    Db(#[from] rusqlite::Error),
22
23    #[error("Serde error: {0}")]
24    Serde(#[from] serde_json::Error),
25
26    #[error("Render error: {0}")]
27    Render(String),
28
29    #[error(transparent)]
30    Core(#[from] finance_core::error::CoreError),
31
32    #[error("{0}")]
33    Other(String),
34}
35
36impl AppError {
37    pub fn exit_code(&self) -> i32 {
38        match self {
39            Self::InvalidInput(_) | Self::Ambiguous(_) | Self::NotFound(_) => 3,
40            Self::Config(_) => 2,
41            _ => 1,
42        }
43    }
44
45    pub fn error_code(&self) -> &'static str {
46        match self {
47            Self::InvalidInput(_) => "invalid_input",
48            Self::Ambiguous(_) => "ambiguous",
49            Self::Config(_) => "config_error",
50            Self::NotFound(_) => "not_found",
51            Self::Io(_) => "io_error",
52            Self::Db(_) => "db_error",
53            Self::Serde(_) => "serde_error",
54            Self::Render(_) => "render_error",
55            Self::Core(_) => "core_error",
56            Self::Other(_) => "other",
57        }
58    }
59
60    pub fn suggestion(&self) -> &'static str {
61        match self {
62            Self::InvalidInput(_) => "Check arguments with: contract --help",
63            Self::Ambiguous(_) => "Use the full slug or a more specific identifier",
64            Self::Config(_) => "Check config with: contract config show",
65            Self::NotFound(_) => "List available entities with: contract <kind> list",
66            Self::Io(_) => "Retry the command",
67            Self::Db(_) => "Check database integrity: contract doctor",
68            Self::Render(_) => "Typst render failed — run: contract doctor",
69            _ => "",
70        }
71    }
72}
73
74pub type Result<T> = std::result::Result<T, AppError>;