Skip to main content

docsrs_cli/error/
classify.rs

1//! Classification: which [`ErrorKind`] a failure is, and whether to retry it.
2//!
3//! Split out of [`super::detail`] when that file crossed the 500-line ceiling.
4//! The division is by responsibility rather than by size: `detail.rs` is the
5//! catalogue of *what can fail*, and this file is the single place deciding
6//! *how each failure is reported*. Keeping them together meant every new
7//! failure shape grew the same file as every new classification rule.
8//!
9//! Deriving the kind here, instead of letting each call site pass one, is why a
10//! single detail can never surface as two different kinds from two different
11//! places.
12
13use super::detail::ErrorDetail;
14use super::vocab::{InternalOp, IoCause, IoOp};
15use super::{ErrorKind, ValueSource};
16
17impl ErrorDetail {
18    /// Canonical [`ErrorKind`] for this failure.
19    ///
20    /// Derived here rather than passed by the caller so one detail can never be
21    /// reported as two different kinds from two different call sites.
22    pub fn kind(&self) -> ErrorKind {
23        match self {
24            // Shape shared by command input and operator config: the subject
25            // decides which, so the exit code names the layer that needs fixing.
26            Self::Empty { subject }
27            | Self::TooLong { subject, .. }
28            | Self::Invalid { subject, .. }
29            | Self::ControlCharacters { subject }
30            | Self::ContainsWhitespace { subject, .. } => {
31                if subject.is_operator_config() {
32                    ErrorKind::Config
33                } else {
34                    ErrorKind::InvalidInput
35                }
36            }
37            Self::MustBeAtLeastOneSecond { source, .. } | Self::AboveHardMaximum { source, .. } => {
38                match source {
39                    ValueSource::CommandLine => ErrorKind::InvalidInput,
40                    ValueSource::ConfigFile => ErrorKind::Config,
41                }
42            }
43
44            Self::ItemPathNoSegments
45            | Self::ItemPathMissingItemName
46            | Self::CrateRefMultipleAt
47            | Self::CrateRefEmptyName
48            | Self::CrateRefEmptyVersion
49            | Self::VersionBuildMetadata
50            | Self::VersionVPrefix
51            | Self::UnknownMatchMode { .. }
52            | Self::UnknownItemType { .. }
53            | Self::UnsupportedLang { .. }
54            | Self::InvalidFilterExpression { .. }
55            | Self::ModuleFilterUnsupported
56            | Self::PageBelowOne
57            | Self::PerPageOutOfRange { .. }
58            | Self::MemberKindNeedsParent { .. }
59            | Self::ItemPathSegmentCharset { .. }
60            | Self::ConflictingVersions { .. } => ErrorKind::InvalidInput,
61
62            Self::NotVisibleAscii { .. }
63            | Self::OriginBadScheme { .. }
64            | Self::OriginMissingHost { .. }
65            | Self::ConfigDirUnresolved
66            | Self::CacheDirUnresolved
67            | Self::ConfigTomlInvalid
68            | Self::ConfigTomlNotUtf8
69            | Self::ConfigTomlTooLarge { .. }
70            | Self::UserAgentHeaderInvalid
71            | Self::ConfigAlreadyExists { .. }
72            | Self::OriginNotAllowlisted { .. } => ErrorKind::Config,
73
74            Self::JsonFormatConflict
75            | Self::UnknownSchemaCommand { .. }
76            | Self::AmbientTargetRefused { .. }
77            | Self::ClapUsage { .. } => ErrorKind::Usage,
78
79            Self::HttpStatus { status, .. } => match status {
80                400 => ErrorKind::InvalidInput,
81                404 => ErrorKind::NotFound,
82                408 => ErrorKind::Timeout,
83                429 => ErrorKind::RateLimited,
84                500 | 502 | 503 | 504 => ErrorKind::Unavailable,
85                _ => ErrorKind::Network,
86            },
87
88            Self::HostNotAllowlisted { .. }
89            | Self::RedirectLimitExceeded
90            | Self::HttpClientBuild
91            | Self::BodyRead
92            | Self::BodyReserveFailed { .. } => ErrorKind::Network,
93
94            Self::BodyOverBudget { .. }
95            | Self::CachedBodyOverBudget { .. }
96            | Self::OutputOverBudget => ErrorKind::Budget,
97
98            Self::BodyNotUtf8
99            | Self::UnexpectedContentType { .. }
100            | Self::HtmlToMarkdown
101            | Self::CratesIoJson
102            | Self::HitJoinFailed
103            | Self::HitBaseInvalid => ErrorKind::Parse,
104
105            Self::AssocParentPageNotFound
106            | Self::AssocAnchorMissing { .. }
107            | Self::AssocAnchorEmpty { .. } => ErrorKind::NotFound,
108
109            Self::HttpRequestFailed { kind, .. } => *kind,
110
111            Self::Interrupted => ErrorKind::Interrupted,
112            Self::Terminated => ErrorKind::Terminated,
113            Self::BrokenPipe => ErrorKind::BrokenPipe,
114            Self::WallClockTimeout { .. } => ErrorKind::Timeout,
115
116            // A full disk or a read-only mount describes the machine, never a
117            // defect in this binary, so it must not arrive as `internal`.
118            Self::Io { .. } => ErrorKind::Io,
119            Self::Internal { op } => match op {
120                InternalOp::SyntheticParseFailure => ErrorKind::Parse,
121                _ => ErrorKind::Internal,
122            },
123
124            // Suggestions never change what failed, only how it is explained.
125            Self::WithSuggestions { base, .. } => base.kind(),
126        }
127    }
128
129    /// Build a filesystem failure, classifying the OS cause at the call site.
130    ///
131    /// The classification has to happen here because this is the last place the
132    /// [`std::io::Error`] exists. One layer up there is only an [`ErrorKind`],
133    /// and `ENOSPC` and `EACCES` share it while deserving opposite answers.
134    pub fn io(op: IoOp, path: Option<String>, err: &std::io::Error) -> Self {
135        Self::Io {
136            op,
137            path,
138            cause: IoCause::of(err),
139        }
140    }
141
142    /// Whether an agent may retry the invocation that produced this failure.
143    ///
144    /// Every kind but [`crate::error::ErrorKind::Io`] answers from the kind alone. Filesystem
145    /// failure is the one case where two opposite answers share a kind, so the
146    /// cause captured at construction wins.
147    pub fn retryable(&self) -> bool {
148        match self {
149            Self::Io { cause, .. } => cause.retryable(),
150            Self::WithSuggestions { base, .. } => base.retryable(),
151            other => other.kind().retryable(),
152        }
153    }
154}