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