Skip to main content

snip/
error.rs

1use std::fmt;
2
3pub type Result<T> = std::result::Result<T, SnipError>;
4
5#[derive(Clone, Copy, Debug, Eq, PartialEq)]
6pub enum ErrorKind {
7    Io,
8    Usage,
9    NoLibrary,
10    NotFound,
11    Conflict,
12    Validation,
13}
14
15impl ErrorKind {
16    pub fn code(self) -> &'static str {
17        match self {
18            Self::Io => "io_error",
19            Self::Usage => "usage_error",
20            Self::NoLibrary => "no_library",
21            Self::NotFound => "not_found",
22            Self::Conflict => "conflict",
23            Self::Validation => "validation_error",
24        }
25    }
26
27    pub fn exit_code(self) -> i32 {
28        match self {
29            Self::Io => 1,
30            Self::Usage => 2,
31            Self::NoLibrary | Self::NotFound => 3,
32            Self::Conflict => 4,
33            Self::Validation => 5,
34        }
35    }
36}
37
38#[derive(Debug)]
39pub struct SnipError {
40    pub kind: ErrorKind,
41    pub message: String,
42    pub hint: Option<String>,
43}
44
45impl SnipError {
46    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
47        Self {
48            kind,
49            message: message.into(),
50            hint: None,
51        }
52    }
53
54    pub fn io(message: impl Into<String>) -> Self {
55        Self::new(ErrorKind::Io, message)
56    }
57
58    pub fn usage(message: impl Into<String>) -> Self {
59        Self::new(ErrorKind::Usage, message)
60    }
61
62    pub fn not_found(message: impl Into<String>) -> Self {
63        Self::new(ErrorKind::NotFound, message)
64    }
65
66    pub fn no_library(message: impl Into<String>) -> Self {
67        Self::new(ErrorKind::NoLibrary, message)
68    }
69
70    pub fn conflict(message: impl Into<String>) -> Self {
71        Self::new(ErrorKind::Conflict, message)
72    }
73
74    pub fn validation(message: impl Into<String>) -> Self {
75        Self::new(ErrorKind::Validation, message)
76    }
77
78    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
79        self.hint = Some(hint.into());
80        self
81    }
82}
83
84impl fmt::Display for SnipError {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        f.write_str(&self.message)
87    }
88}
89
90impl std::error::Error for SnipError {}
91
92impl From<std::io::Error> for SnipError {
93    fn from(error: std::io::Error) -> Self {
94        Self::io(error.to_string())
95    }
96}
97
98impl From<toml::de::Error> for SnipError {
99    fn from(error: toml::de::Error) -> Self {
100        Self::validation(error.to_string())
101    }
102}
103
104impl From<toml::ser::Error> for SnipError {
105    fn from(error: toml::ser::Error) -> Self {
106        Self::validation(error.to_string())
107    }
108}
109
110impl From<serde_json::Error> for SnipError {
111    fn from(error: serde_json::Error) -> Self {
112        Self::validation(error.to_string())
113    }
114}