Skip to main content

fprint_core/
error.rs

1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Error type for the core API.
6
7/// Crate result alias.
8pub type Result<T> = core::result::Result<T, Error>;
9
10/// Errors surfaced by [`Backend`]/[`Device`] operations.
11///
12/// A flat *translation vocabulary*, not a source-chaining wrapper: a closed classification
13/// mirroring libfprint's `FpDeviceError` (`FP_DEVICE_ERROR_*`) plus a few transport/proto
14/// buckets. Each backend maps its native failures (glib `GError`, USB errors) onto these
15/// variants, and the daemon remaps them onto D-Bus names; the terminal form is a human-readable
16/// string at that edge. `retry`-class variants correspond to fprintd's `*-retry-scan` /
17/// `*-remove-and-retry` status strings and mean "try again", not "give up".
18///
19/// The boundary variants (`Transport`/`Protocol`/`Other`) carry a `String`, not a `dyn` source:
20/// the vocabulary is closed and value-semantic, so it collapses to strings at the D-Bus edge
21/// rather than chaining a cause.
22///
23/// [`Backend`]: crate::Backend
24/// [`Device`]: crate::Device
25#[derive(Debug, Clone, PartialEq, Eq)]
26#[non_exhaustive]
27pub enum Error {
28    /// No such device, or it went away.
29    NotFound,
30    /// Operation not supported by this device (missing [`crate::DeviceFeature`]).
31    NotSupported,
32    /// Device is busy with another operation.
33    Busy,
34    /// The device was in the wrong state for the request (e.g. not open).
35    ProtoState,
36    /// Operation was cancelled by the caller.
37    Cancelled,
38    /// The user should present the finger again (bad scan, too fast, off-centre, …).
39    RetryScan(RetryReason),
40    /// On-device template storage is full.
41    DataFull,
42    /// A print with this finger is already enrolled (`DUPLICATES_CHECK` devices).
43    DataDuplicate,
44    /// The template does not exist on the device / in the gallery.
45    DataNotFound,
46    /// Low-level transport failure (USB/SPI).
47    Transport(String),
48    /// Protocol/parse failure talking to the sensor.
49    Protocol(String),
50    /// Anything a backend cannot map to the above.
51    Other(String),
52}
53
54/// Why a scan needs to be retried (maps to fprintd `enroll-*`/`verify-*` retry strings).
55///
56/// Mirrors libfprint's open-ended `FpDeviceRetry` vocabulary, so it is `#[non_exhaustive]`:
57/// a future retry reason must not be a breaking change for downstream matchers.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum RetryReason {
61    /// `FP_DEVICE_RETRY_GENERAL`: the scan was unusable, with no more specific cause.
62    General,
63    /// `FP_DEVICE_RETRY_TOO_SHORT`: the swipe covered too little of the sensor.
64    TooShort,
65    /// `FP_DEVICE_RETRY_CENTER_FINGER`: the finger was off the centre of the sensor.
66    NotCentered,
67    /// `FP_DEVICE_RETRY_REMOVE_FINGER`: the finger must leave the sensor before retrying.
68    RemoveAndRetry,
69    /// `FP_DEVICE_RETRY_TOO_FAST`: the swipe was too quick to digitize.
70    TooFast,
71}
72
73impl core::fmt::Display for Error {
74    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
75        match self {
76            Error::NotFound => f.write_str("device not found"),
77            Error::NotSupported => f.write_str("operation not supported by device"),
78            Error::Busy => f.write_str("device busy"),
79            Error::ProtoState => f.write_str("device in wrong state for operation"),
80            Error::Cancelled => f.write_str("operation cancelled"),
81            Error::RetryScan(r) => write!(f, "retry scan: {r:?}"),
82            Error::DataFull => f.write_str("on-device storage full"),
83            Error::DataDuplicate => f.write_str("finger already enrolled"),
84            Error::DataNotFound => f.write_str("template not found"),
85            Error::Transport(m) => write!(f, "transport error: {m}"),
86            Error::Protocol(m) => write!(f, "protocol error: {m}"),
87            Error::Other(m) => write!(f, "{m}"),
88        }
89    }
90}
91
92impl std::error::Error for Error {}
93
94#[cfg(test)]
95mod tests {
96    use super::{Error, RetryReason};
97
98    /// **Every [`Error`] variant renders a message that carries its payload.**
99    ///
100    /// The `match` is the point: it has no wildcard arm, and `#[non_exhaustive]` does not apply
101    /// inside the defining crate, so a new variant makes this test *fail to compile* until someone
102    /// states what its message must contain. The compiler does the enumerating.
103    ///
104    /// Only the shape is asserted — that `Transport(m)` surfaces `m`, not the words around it. The
105    /// prose is not an interface and no test should freeze it.
106    ///
107    /// The honest limit: `samples` is hand-written, so a new variant is compile-forced into the
108    /// match but must still be added there to be exercised at runtime.
109    #[test]
110    fn every_error_variant_renders_its_payload() {
111        const MARKER: &str = "cafef00d-marker";
112        // Every retry reason, since `RetryScan` renders the reason rather than a fixed string.
113        let reasons = [
114            RetryReason::General,
115            RetryReason::TooShort,
116            RetryReason::NotCentered,
117            RetryReason::RemoveAndRetry,
118            RetryReason::TooFast,
119        ];
120        let samples = [
121            Error::NotFound,
122            Error::NotSupported,
123            Error::Busy,
124            Error::ProtoState,
125            Error::Cancelled,
126            Error::DataFull,
127            Error::DataDuplicate,
128            Error::DataNotFound,
129            Error::Transport(MARKER.to_string()),
130            Error::Protocol(MARKER.to_string()),
131            Error::Other(MARKER.to_string()),
132        ];
133
134        let samples: Vec<Error> = samples
135            .into_iter()
136            .chain(reasons.map(Error::RetryScan))
137            .collect();
138
139        for error in &samples {
140            let rendered = error.to_string();
141            assert!(!rendered.trim().is_empty(), "{error:?} renders nothing");
142
143            match error {
144                // Payload-free variants: a non-empty message is the whole contract.
145                Error::NotFound
146                | Error::NotSupported
147                | Error::Busy
148                | Error::ProtoState
149                | Error::Cancelled
150                | Error::DataFull
151                | Error::DataDuplicate
152                | Error::DataNotFound => {}
153                // Payload-carrying variants must not swallow the payload.
154                Error::RetryScan(reason) => {
155                    let shown = format!("{reason:?}");
156                    assert!(rendered.contains(&shown), "{rendered:?} drops {shown:?}");
157                }
158                Error::Transport(message) | Error::Protocol(message) | Error::Other(message) => {
159                    assert!(rendered.contains(message), "{rendered:?} drops {message:?}");
160                }
161            }
162        }
163    }
164
165    /// `Display` distinguishes the payload-free variants from each other: a copy-paste that gave
166    /// two of them the same message would leave a caller unable to tell them apart in a log.
167    #[test]
168    fn payload_free_variants_render_distinctly() {
169        let messages = [
170            Error::NotFound.to_string(),
171            Error::NotSupported.to_string(),
172            Error::Busy.to_string(),
173            Error::ProtoState.to_string(),
174            Error::Cancelled.to_string(),
175            Error::DataFull.to_string(),
176            Error::DataDuplicate.to_string(),
177            Error::DataNotFound.to_string(),
178        ];
179        for (i, a) in messages.iter().enumerate() {
180            for b in &messages[i + 1..] {
181                assert_ne!(a, b, "two variants share the message {a:?}");
182            }
183        }
184    }
185}