Skip to main content

docsrs_cli/error/
mod.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// ── Named process exit codes (sysexits-inspired + signal/convention) ─────────
38// Every `ExitCode::from(N)` / `process::exit(N)` in product code must use these
39// (or [`crate::error::ErrorKind::exit_code`]) — never raw numeric literals for exit status.
40
41/// Clap / argv usage error (sysexits `EX_USAGE`).
42pub const EXIT_USAGE: u8 = 64;
43/// Domain validation failure (invalid crate name, path, pagination).
44pub const EXIT_INVALID_INPUT: u8 = 65;
45/// Remote resource missing (HTTP 404).
46pub const EXIT_NOT_FOUND: u8 = 66;
47/// Rate limit or temporary remote unavailability (HTTP 429/5xx).
48pub const EXIT_UNAVAILABLE: u8 = 69;
49/// Unexpected internal failure.
50pub const EXIT_INTERNAL: u8 = 70;
51/// Transport / network failure or local body budget.
52pub const EXIT_NETWORK: u8 = 74;
53/// Local filesystem failure (sysexits `EX_IOERR`, the original meaning of 74).
54///
55/// Three kinds share this code and the contract has always said so: 74 is
56/// ambiguous until `error.kind` is read. `network` is retryable, `budget` never
57/// is, and `io` depends on the OS cause. Giving filesystem failure its own code
58/// would buy nothing an agent cannot already read, and would add a number to a
59/// contract that promises stable exit codes.
60pub const EXIT_IO: u8 = EXIT_NETWORK;
61/// Local configuration error (XDG TOML, origins).
62pub const EXIT_CONFIG: u8 = 78;
63/// Wall-clock deadline exceeded.
64pub const EXIT_TIMEOUT: u8 = 124;
65/// SIGINT / Ctrl-C cooperative cancel.
66pub const EXIT_INTERRUPTED: u8 = 130;
67/// stdout EPIPE / broken pipe.
68pub const EXIT_BROKEN_PIPE: u8 = 141;
69/// SIGTERM / SIGHUP terminate.
70pub const EXIT_TERMINATED: u8 = 143;
71
72/// Map a filesystem failure onto the catalogue, keeping the path that failed.
73///
74/// Sixteen call sites across the cache and the rate limiter used to build
75/// [`ErrorDetail::Io`] inline with `path: None`, every one of them holding the
76/// path it had just tried to open. An operator whose disk filled learned which
77/// *operation* failed and never which *file*, which is the one fact needed to
78/// act. Routing them through one closure fixes that and puts OS-cause
79/// classification in a single place at the same time.
80///
81/// ```no_run
82/// # use std::path::Path;
83/// # use docsrs_cli::error::{io_at, IoOp};
84/// std::fs::create_dir_all("/tmp/x").map_err(io_at(IoOp::CreateDir, Path::new("/tmp/x")))?;
85/// # Ok::<(), docsrs_cli::error::AppError>(())
86/// ```
87pub fn io_at(op: IoOp, path: &std::path::Path) -> impl FnOnce(std::io::Error) -> AppError {
88    let path = path.display().to_string();
89    move |e| {
90        let detail = ErrorDetail::io(op, Some(path), &e);
91        AppError::of_with_source(detail, e)
92    }
93}
94
95/// Canonical error kinds exposed in JSON envelopes.
96///
97/// Marked `#[non_exhaustive]` so new kinds can ship without a SemVer major break
98/// for external `match` consumers of this library.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
100#[serde(rename_all = "snake_case")]
101#[non_exhaustive]
102pub enum ErrorKind {
103    /// Clap usage / argv error (exit 64).
104    Usage,
105    /// Invalid domain input such as crate name or path (exit 65).
106    InvalidInput,
107    /// Remote resource missing (exit 66).
108    NotFound,
109    /// HTTP 429 rate limit (exit 69, retryable).
110    RateLimited,
111    /// Remote 5xx or temporary outage (exit 69, retryable).
112    Unavailable,
113    /// Wall-clock deadline exceeded (exit 124, retryable).
114    Timeout,
115    /// Transport / unexpected HTTP failure (exit 74, retryable).
116    Network,
117    /// Local body/output budget exceeded (exit 74, **not** retryable).
118    ///
119    /// Permanent for the same config: raising `--max-body-bytes` (or lowering
120    /// the remote payload) is required — agents must not auto-retry.
121    Budget,
122    /// Body parse failure (exit 65).
123    Parse,
124    /// Local configuration error (exit 78).
125    Config,
126    /// Local filesystem failure caused by the environment (exit 74).
127    ///
128    /// A full disk, a read-only mount or a directory the process cannot enter
129    /// are facts about the machine, not defects in this binary. They used to
130    /// arrive as [`Self::Internal`], which tells an agent to report a bug in a
131    /// CLI that behaved correctly, and as `retryable: false`, which is wrong the
132    /// moment the operator frees a block. Retryability here comes from the OS
133    /// cause carried in the detail, so read [`AppError::retryable`] rather than
134    /// [`Self::retryable`], which can only answer for the kind.
135    Io,
136    /// Unexpected internal failure (exit 70).
137    Internal,
138    /// SIGINT / Ctrl-C
139    Interrupted,
140    /// SIGTERM graceful cancel
141    Terminated,
142    /// stdout write hit a closed pipe (EPIPE / SIGPIPE)
143    BrokenPipe,
144}
145
146impl ErrorKind {
147    /// Stable snake_case identifier for JSON `error.kind`.
148    pub fn as_str(self) -> &'static str {
149        match self {
150            Self::Usage => "usage",
151            Self::InvalidInput => "invalid_input",
152            Self::NotFound => "not_found",
153            Self::RateLimited => "rate_limited",
154            Self::Unavailable => "unavailable",
155            Self::Timeout => "timeout",
156            Self::Network => "network",
157            Self::Budget => "budget",
158            Self::Parse => "parse",
159            Self::Config => "config",
160            Self::Io => "io",
161            Self::Internal => "internal",
162            Self::Interrupted => "interrupted",
163            Self::Terminated => "terminated",
164            Self::BrokenPipe => "broken_pipe",
165        }
166    }
167
168    /// Process exit code for this kind.
169    pub fn exit_code(self) -> u8 {
170        match self {
171            Self::Usage => EXIT_USAGE,
172            Self::InvalidInput => EXIT_INVALID_INPUT,
173            Self::NotFound => EXIT_NOT_FOUND,
174            Self::RateLimited | Self::Unavailable => EXIT_UNAVAILABLE,
175            Self::Network | Self::Budget => EXIT_NETWORK,
176            Self::Timeout => EXIT_TIMEOUT,
177            Self::Parse => EXIT_INVALID_INPUT,
178            Self::Config => EXIT_CONFIG,
179            Self::Io => EXIT_IO,
180            Self::Internal => EXIT_INTERNAL,
181            Self::Interrupted => EXIT_INTERRUPTED,
182            Self::Terminated => EXIT_TERMINATED,
183            Self::BrokenPipe => EXIT_BROKEN_PIPE,
184        }
185    }
186
187    /// Whether an agent may retry the same invocation after backoff.
188    ///
189    /// [`Self::Io`] answers `false` here and means "unknown, ask the detail":
190    /// the kind alone cannot tell a full disk from a permission denial. The wire
191    /// field comes from [`AppError::retryable`], which reads the cause, so this
192    /// conservative answer never reaches an envelope.
193    pub fn retryable(self) -> bool {
194        matches!(
195            self,
196            Self::RateLimited | Self::Unavailable | Self::Timeout | Self::Network
197        )
198    }
199
200    /// Alias of [`Self::retryable`] (Rules Rust checklist name `is_retryable`).
201    pub fn is_retryable(self) -> bool {
202        self.retryable()
203    }
204
205    /// Permanent for agent auto-retry (complement of [`Self::is_retryable`]).
206    ///
207    /// Cancel / broken-pipe kinds are permanent: do not re-issue the same command
208    /// as if the remote failed.
209    pub fn is_permanent(self) -> bool {
210        !self.retryable()
211    }
212
213    /// Detailed retry category (Rules Rust checklist `retry_kind`).
214    pub fn retry_kind(self) -> crate::retry::RetryKind {
215        use crate::retry::RetryKind;
216        match self {
217            Self::RateLimited => RetryKind::RateLimited,
218            Self::Unavailable => RetryKind::TransientServer,
219            Self::Timeout => RetryKind::Timeout,
220            Self::Network => RetryKind::TransientNetwork,
221            _ => RetryKind::Permanent,
222        }
223    }
224}
225
226/// Application error with structured kind for agents.
227///
228/// # Display
229///
230/// Prints only the technical English `message` field (lowercase, no trailing
231/// period). Walk [`std::error::Error::source`] for the cause chain; do not
232/// duplicate the cause text in `message`.
233///
234/// # Clone
235///
236/// Source is held in [`Arc`] so clones share the cause without re-boxing.
237#[derive(Debug, Error, Clone)]
238#[non_exhaustive]
239pub enum AppError {
240    /// Structured error used by all library and CLI paths.
241    #[error("{message}")]
242    Structured {
243        /// Canonical error kind for exit codes and JSON.
244        kind: ErrorKind,
245        /// Technical English message (never localized) — the JSON wire field.
246        message: String,
247        /// Typed catalogue entry this error was built from.
248        ///
249        /// Not optional: the string constructors were removed, so every error
250        /// carries its data and therefore both renderings. Boxed to keep
251        /// `AppError` small, since most values are moved around as `Result`
252        /// payloads rather than inspected.
253        detail: Box<ErrorDetail>,
254        /// Optional Retry-After hint from HTTP 429 / 503.
255        retry_after_secs: Option<u64>,
256        /// Optional lower-level cause (shared via [`Arc`] for [`Clone`]).
257        #[source]
258        source: Option<Arc<dyn std::error::Error + Send + Sync>>,
259    },
260}
261
262impl AppError {
263    /// Build an error from the typed catalogue.
264    ///
265    /// This is the constructor product code should use. Both the [`ErrorKind`]
266    /// and the English wire message are derived from `detail`, so one failure
267    /// can never be reported as two different kinds from two call sites, and it
268    /// can never ship without a pt-BR rendering — the renderer's `match` has no
269    /// `_` arm, so a missing translation fails to compile.
270    pub fn of(detail: ErrorDetail) -> Self {
271        Self::Structured {
272            kind: detail.kind(),
273            message: render::render_en(&detail),
274            detail: Box::new(detail),
275            retry_after_secs: None,
276            source: None,
277        }
278    }
279
280    /// [`Self::of`] with a preserved lower-level cause.
281    pub fn of_with_source(
282        detail: ErrorDetail,
283        source: impl std::error::Error + Send + Sync + 'static,
284    ) -> Self {
285        Self::Structured {
286            kind: detail.kind(),
287            message: render::render_en(&detail),
288            detail: Box::new(detail),
289            retry_after_secs: None,
290            source: Some(Arc::new(source)),
291        }
292    }
293
294    /// Render this error in `locale`, for human stderr.
295    ///
296    /// Always available in both languages: the catalogue is the only way to
297    /// build an `AppError`, and its pt-BR renderer is exhaustive.
298    pub fn localized(&self, locale: crate::i18n::Locale) -> String {
299        match self {
300            Self::Structured {
301                detail, message, ..
302            } => match locale {
303                crate::i18n::Locale::PtBr => render::render_pt_br(detail),
304                crate::i18n::Locale::En => message.clone(),
305            },
306        }
307    }
308
309    /// Attach optional Retry-After seconds (HTTP 429 / 503).
310    pub fn with_retry_after(mut self, secs: u64) -> Self {
311        let Self::Structured {
312            retry_after_secs, ..
313        } = &mut self;
314        *retry_after_secs = Some(secs);
315        self
316    }
317
318    /// SIGINT cancel.
319    pub fn interrupted() -> Self {
320        Self::of(ErrorDetail::Interrupted)
321    }
322
323    /// SIGTERM cancel.
324    pub fn terminated() -> Self {
325        Self::of(ErrorDetail::Terminated)
326    }
327
328    /// stdout closed by the reader (pipe consumer exited).
329    pub fn broken_pipe() -> Self {
330        Self::of(ErrorDetail::BrokenPipe)
331    }
332
333    /// Returns the canonical error kind.
334    pub fn kind(&self) -> ErrorKind {
335        match self {
336            Self::Structured { kind, .. } => *kind,
337        }
338    }
339
340    /// Typed catalogue entry this error carries.
341    ///
342    /// Lets a caller wrap one failure inside another (suggestions, context)
343    /// without flattening it to a string and losing the pt-BR rendering.
344    pub fn detail(&self) -> &ErrorDetail {
345        match self {
346            Self::Structured { detail, .. } => detail,
347        }
348    }
349
350    /// Returns the technical English message.
351    pub fn message(&self) -> &str {
352        match self {
353            Self::Structured { message, .. } => message,
354        }
355    }
356
357    /// Returns optional Retry-After seconds when present.
358    pub fn retry_after_secs(&self) -> Option<u64> {
359        match self {
360            Self::Structured {
361                retry_after_secs, ..
362            } => *retry_after_secs,
363        }
364    }
365
366    /// Whether an agent may retry the same invocation after backoff.
367    ///
368    /// This is the value that reaches `error.retryable` on the wire. For
369    /// filesystem failures it comes from the OS cause captured where the
370    /// [`std::io::Error`] was still in hand, because `ENOSPC` and `EACCES` are
371    /// the same [`ErrorKind`] and opposite answers.
372    pub fn retryable(&self) -> bool {
373        self.detail().retryable()
374    }
375
376    /// Ranked `--suggest` alternatives carried by this failure, if any.
377    ///
378    /// Only the outermost detail is inspected: the recovery ladder wraps a
379    /// not-found in exactly one [`ErrorDetail::WithSuggestions`], and a nested
380    /// one would mean two competing lists with no rule for which wins.
381    pub fn suggestions(&self) -> Option<&[Suggestion]> {
382        match self.detail() {
383            ErrorDetail::WithSuggestions { suggestions, .. } => Some(suggestions),
384            _ => None,
385        }
386    }
387
388    /// Alias of [`Self::retryable`] (Rules Rust checklist name `is_retryable`).
389    pub fn is_retryable(&self) -> bool {
390        self.retryable()
391    }
392
393    /// Permanent for agent auto-retry (complement of [`Self::is_retryable`]).
394    pub fn is_permanent(&self) -> bool {
395        !self.retryable()
396    }
397
398    /// Detailed retry category (Rules Rust checklist `retry_kind`).
399    pub fn retry_kind(&self) -> crate::retry::RetryKind {
400        self.kind().retry_kind()
401    }
402
403    /// Maps this error to a process [`ExitCode`].
404    pub fn exit_code(&self) -> ExitCode {
405        ExitCode::from(self.kind().exit_code())
406    }
407
408    /// Map remote HTTP status to a domain error.
409    ///
410    /// `body_hint` must be a short, non-sensitive context label (e.g. endpoint
411    /// name or `"retries exhausted"`), never a raw response body or credential.
412    pub fn from_http_status(status: u16, body_hint: &str) -> Self {
413        // Status-to-kind mapping lives in `ErrorDetail::kind`, so the wire text
414        // and the exit code can never disagree about what a 429 means.
415        Self::of(ErrorDetail::HttpStatus {
416            status,
417            hint: body_hint.to_string(),
418        })
419    }
420}
421
422/// Result alias for library operations.
423pub type AppResult<T> = Result<T, AppError>;
424
425mod classify;
426mod detail;
427mod render;
428mod suggestion;
429mod vocab;
430
431#[cfg(test)]
432mod tests;
433
434pub use detail::ErrorDetail;
435pub use suggestion::Suggestion;
436pub use vocab::{
437    AllowlistStage, ContentKind, DestructiveEffect, InternalOp, IoCause, IoOp, Subject, ValueSource,
438};