Skip to main content

docsrs_cli/
error.rs

1//! Error types and exit-code mapping for docsrs-cli.
2//!
3//! # Model (Rules Rust — error handling)
4//!
5//! - Recoverable failures are [`AppError`] / [`AppResult`] (I/O, network, parse, validation).
6//! - [`ErrorKind`] is the stable discriminant for exit codes and JSON `error.kind`.
7//! - [`std::error::Error::source`] preserves the lower-level cause when present.
8//! - Display messages are technical English: lowercase, no trailing period, no secrets.
9//! - Panic is reserved for static invariants (hardcoded regex / CSS selectors).
10//! - Library API: typed `thiserror` enum, not `anyhow` / `Box<dyn Error>` as the public `E`.
11//!
12//! See `docs/decisions/0002-error-model.md`.
13//!
14//! # Errors
15//!
16//! | Kind | Exit | Retryable |
17//! |------|------|-----------|
18//! | usage | 64 | no |
19//! | invalid_input | 65 | no |
20//! | not_found | 66 | no |
21//! | rate_limited / unavailable | 69 | yes |
22//! | network | 74 | yes |
23//! | timeout | 124 | yes |
24//! | parse | 65 | no |
25//! | config | 78 | no |
26//! | internal | 70 | no |
27//! | interrupted (SIGINT) | 130 | no |
28//! | terminated (SIGTERM) | 143 | no |
29//! | broken_pipe (stdout EPIPE) | 141 | no |
30
31use std::process::ExitCode;
32use std::sync::Arc;
33
34use thiserror::Error;
35
36/// Canonical error kinds exposed in JSON envelopes.
37///
38/// Marked `#[non_exhaustive]` so new kinds can ship without a SemVer major break
39/// for external `match` consumers of this library.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
41#[serde(rename_all = "snake_case")]
42#[non_exhaustive]
43pub enum ErrorKind {
44    /// Clap usage / argv error (exit 64).
45    Usage,
46    /// Invalid domain input such as crate name or path (exit 65).
47    InvalidInput,
48    /// Remote resource missing (exit 66).
49    NotFound,
50    /// HTTP 429 rate limit (exit 69, retryable).
51    RateLimited,
52    /// Remote 5xx or temporary outage (exit 69, retryable).
53    Unavailable,
54    /// Wall-clock deadline exceeded (exit 124, retryable).
55    Timeout,
56    /// Transport / unexpected HTTP failure (exit 74, retryable).
57    Network,
58    /// Body parse failure (exit 65).
59    Parse,
60    /// Local configuration error (exit 78).
61    Config,
62    /// Unexpected internal failure (exit 70).
63    Internal,
64    /// SIGINT / Ctrl-C
65    Interrupted,
66    /// SIGTERM graceful cancel
67    Terminated,
68    /// stdout write hit a closed pipe (EPIPE / SIGPIPE)
69    BrokenPipe,
70}
71
72impl ErrorKind {
73    /// Stable snake_case identifier for JSON `error.kind`.
74    pub fn as_str(self) -> &'static str {
75        match self {
76            Self::Usage => "usage",
77            Self::InvalidInput => "invalid_input",
78            Self::NotFound => "not_found",
79            Self::RateLimited => "rate_limited",
80            Self::Unavailable => "unavailable",
81            Self::Timeout => "timeout",
82            Self::Network => "network",
83            Self::Parse => "parse",
84            Self::Config => "config",
85            Self::Internal => "internal",
86            Self::Interrupted => "interrupted",
87            Self::Terminated => "terminated",
88            Self::BrokenPipe => "broken_pipe",
89        }
90    }
91
92    /// Process exit code for this kind.
93    pub fn exit_code(self) -> u8 {
94        match self {
95            Self::Usage => 64,
96            Self::InvalidInput => 65,
97            Self::NotFound => 66,
98            Self::RateLimited | Self::Unavailable => 69,
99            Self::Network => 74,
100            Self::Timeout => 124,
101            Self::Parse => 65,
102            Self::Config => 78,
103            Self::Internal => 70,
104            Self::Interrupted => 130,
105            Self::Terminated => 143,
106            Self::BrokenPipe => 141,
107        }
108    }
109
110    /// Whether an agent may retry the same invocation after backoff.
111    pub fn retryable(self) -> bool {
112        matches!(
113            self,
114            Self::RateLimited | Self::Unavailable | Self::Timeout | Self::Network
115        )
116    }
117
118    /// Alias of [`Self::retryable`] (Rules Rust checklist name `is_retryable`).
119    pub fn is_retryable(self) -> bool {
120        self.retryable()
121    }
122
123    /// Permanent for agent auto-retry (complement of [`Self::is_retryable`]).
124    ///
125    /// Cancel / broken-pipe kinds are permanent: do not re-issue the same command
126    /// as if the remote failed.
127    pub fn is_permanent(self) -> bool {
128        !self.retryable()
129    }
130}
131
132/// Application error with structured kind for agents.
133///
134/// # Display
135///
136/// Prints only the technical English `message` field (lowercase, no trailing
137/// period). Walk [`std::error::Error::source`] for the cause chain; do not
138/// duplicate the cause text in `message`.
139///
140/// # Clone
141///
142/// Source is held in [`Arc`] so clones share the cause without re-boxing.
143#[derive(Debug, Error, Clone)]
144#[non_exhaustive]
145pub enum AppError {
146    /// Structured error used by all library and CLI paths.
147    #[error("{message}")]
148    Structured {
149        /// Canonical error kind for exit codes and JSON.
150        kind: ErrorKind,
151        /// Technical English message (never localized).
152        message: String,
153        /// Optional Retry-After hint from HTTP 429 / 503.
154        retry_after_secs: Option<u64>,
155        /// Optional lower-level cause (shared via [`Arc`] for [`Clone`]).
156        #[source]
157        source: Option<Arc<dyn std::error::Error + Send + Sync>>,
158    },
159}
160
161impl AppError {
162    /// Build a structured error without a source chain.
163    ///
164    /// # Errors
165    ///
166    /// This constructor never fails; the returned value is the error itself.
167    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
168        Self::Structured {
169            kind,
170            message: message.into(),
171            retry_after_secs: None,
172            source: None,
173        }
174    }
175
176    /// Build a structured error with a source chain (cause preserved).
177    ///
178    /// The cause is available via [`std::error::Error::source`] and is not
179    /// duplicated in `message`.
180    pub fn with_source(
181        kind: ErrorKind,
182        message: impl Into<String>,
183        source: impl std::error::Error + Send + Sync + 'static,
184    ) -> Self {
185        Self::Structured {
186            kind,
187            message: message.into(),
188            retry_after_secs: None,
189            source: Some(Arc::new(source)),
190        }
191    }
192
193    /// Attach optional Retry-After seconds (HTTP 429 / 503).
194    pub fn with_retry_after(mut self, secs: u64) -> Self {
195        let Self::Structured {
196            retry_after_secs, ..
197        } = &mut self;
198        *retry_after_secs = Some(secs);
199        self
200    }
201
202    /// SIGINT cancel.
203    pub fn interrupted() -> Self {
204        Self::new(ErrorKind::Interrupted, "interrupted by SIGINT")
205    }
206
207    /// SIGTERM cancel.
208    pub fn terminated() -> Self {
209        Self::new(ErrorKind::Terminated, "terminated by SIGTERM")
210    }
211
212    /// stdout closed by the reader (pipe consumer exited).
213    pub fn broken_pipe() -> Self {
214        Self::new(ErrorKind::BrokenPipe, "broken pipe writing to stdout")
215    }
216
217    /// Returns the canonical error kind.
218    pub fn kind(&self) -> ErrorKind {
219        match self {
220            Self::Structured { kind, .. } => *kind,
221        }
222    }
223
224    /// Returns the technical English message.
225    pub fn message(&self) -> &str {
226        match self {
227            Self::Structured { message, .. } => message,
228        }
229    }
230
231    /// Returns optional Retry-After seconds when present.
232    pub fn retry_after_secs(&self) -> Option<u64> {
233        match self {
234            Self::Structured {
235                retry_after_secs, ..
236            } => *retry_after_secs,
237        }
238    }
239
240    /// Whether an agent may retry the same invocation after backoff.
241    pub fn retryable(&self) -> bool {
242        self.kind().retryable()
243    }
244
245    /// Alias of [`Self::retryable`] (Rules Rust checklist name `is_retryable`).
246    pub fn is_retryable(&self) -> bool {
247        self.retryable()
248    }
249
250    /// Permanent for agent auto-retry (complement of [`Self::is_retryable`]).
251    pub fn is_permanent(&self) -> bool {
252        self.kind().is_permanent()
253    }
254
255    /// Maps this error to a process [`ExitCode`].
256    pub fn exit_code(&self) -> ExitCode {
257        ExitCode::from(self.kind().exit_code())
258    }
259
260    /// Map remote HTTP status to a domain error.
261    ///
262    /// `body_hint` must be a short, non-sensitive context label (e.g. endpoint
263    /// name or `"retries exhausted"`), never a raw response body or credential.
264    pub fn from_http_status(status: u16, body_hint: &str) -> Self {
265        match status {
266            400 => Self::new(
267                ErrorKind::InvalidInput,
268                format!("bad request from remote: {body_hint}"),
269            ),
270            404 => Self::new(
271                ErrorKind::NotFound,
272                format!("resource not found: {body_hint}"),
273            ),
274            429 => Self::new(
275                ErrorKind::RateLimited,
276                format!("rate limited by remote: {body_hint}"),
277            ),
278            500 | 502 | 503 | 504 => Self::new(
279                ErrorKind::Unavailable,
280                format!("remote unavailable (HTTP {status}): {body_hint}"),
281            ),
282            other => Self::new(
283                ErrorKind::Network,
284                format!("unexpected HTTP status {other}: {body_hint}"),
285            ),
286        }
287    }
288}
289
290/// Result alias for library operations.
291pub type AppResult<T> = Result<T, AppError>;
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    #[test]
298    fn exit_codes_canonical() {
299        assert_eq!(ErrorKind::Usage.exit_code(), 64);
300        assert_eq!(ErrorKind::InvalidInput.exit_code(), 65);
301        assert_eq!(ErrorKind::NotFound.exit_code(), 66);
302        assert_eq!(ErrorKind::RateLimited.exit_code(), 69);
303        assert_eq!(ErrorKind::Network.exit_code(), 74);
304        assert_eq!(ErrorKind::Timeout.exit_code(), 124);
305        assert_eq!(ErrorKind::Interrupted.exit_code(), 130);
306        assert_eq!(ErrorKind::Terminated.exit_code(), 143);
307        assert_eq!(ErrorKind::BrokenPipe.exit_code(), 141);
308        assert_eq!(ErrorKind::Config.exit_code(), 78);
309        assert_eq!(ErrorKind::Internal.exit_code(), 70);
310        assert_eq!(ErrorKind::BrokenPipe.as_str(), "broken_pipe");
311        assert!(!ErrorKind::BrokenPipe.retryable());
312    }
313
314    #[test]
315    fn cancel_helpers() {
316        assert_eq!(AppError::interrupted().kind(), ErrorKind::Interrupted);
317        assert_eq!(AppError::terminated().kind(), ErrorKind::Terminated);
318        assert_eq!(AppError::broken_pipe().kind(), ErrorKind::BrokenPipe);
319        assert_eq!(AppError::broken_pipe().exit_code(), ExitCode::from(141));
320    }
321
322    #[test]
323    fn from_http_status_matrix() {
324        assert_eq!(
325            AppError::from_http_status(400, "x").kind(),
326            ErrorKind::InvalidInput
327        );
328        assert_eq!(
329            AppError::from_http_status(404, "x").kind(),
330            ErrorKind::NotFound
331        );
332        assert_eq!(
333            AppError::from_http_status(429, "x").kind(),
334            ErrorKind::RateLimited
335        );
336        assert_eq!(
337            AppError::from_http_status(503, "x").kind(),
338            ErrorKind::Unavailable
339        );
340        assert_eq!(
341            AppError::from_http_status(418, "x").kind(),
342            ErrorKind::Network
343        );
344        let e = AppError::from_http_status(429, "slow").with_retry_after(7);
345        assert_eq!(e.retry_after_secs(), Some(7));
346        assert!(e.kind().retryable());
347        assert!(e.kind().is_retryable());
348        assert!(!ErrorKind::NotFound.retryable());
349        assert!(ErrorKind::NotFound.is_permanent());
350        assert!(ErrorKind::Interrupted.is_permanent());
351        assert_eq!(ErrorKind::Parse.as_str(), "parse");
352        assert_eq!(ErrorKind::Config.exit_code(), 78);
353    }
354
355    #[test]
356    fn with_source_preserves_kind() {
357        let e = AppError::with_source(ErrorKind::Parse, "bad", std::io::Error::other("inner"));
358        assert_eq!(e.kind(), ErrorKind::Parse);
359        assert_eq!(e.message(), "bad");
360    }
361
362    #[test]
363    fn source_chain_via_std_error() {
364        use std::error::Error as _;
365        let e = AppError::with_source(ErrorKind::Parse, "bad", std::io::Error::other("inner"));
366        let src = e.source().expect("source present");
367        assert!(src.to_string().contains("inner"));
368        // Display is message only — cause is not duplicated.
369        assert_eq!(e.to_string(), "bad");
370        assert!(!e.to_string().contains("inner"));
371    }
372
373    #[test]
374    fn app_error_clone_shares_source() {
375        use std::error::Error as _;
376        let e = AppError::with_source(ErrorKind::Network, "req failed", std::io::Error::other("eof"));
377        let c = e.clone();
378        assert_eq!(c.kind(), ErrorKind::Network);
379        assert_eq!(c.message(), "req failed");
380        assert!(c.source().is_some());
381        assert!(c.is_retryable());
382        assert!(!c.is_permanent());
383        assert!(AppError::new(ErrorKind::NotFound, "missing").is_permanent());
384    }
385
386    #[test]
387    fn display_message_style() {
388        let e = AppError::new(ErrorKind::Config, "invalid config.toml");
389        let s = e.to_string();
390        assert_eq!(s, "invalid config.toml");
391        assert!(!s.ends_with('.'));
392        assert_eq!(s, s.to_ascii_lowercase());
393    }
394}