Skip to main content

webbluetooth_core/
error.rs

1//! Errors, named after the `DOMException`s the Web Bluetooth spec throws.
2//!
3//! Keeping the spec's names — rather than inventing Rust-flavoured ones — means
4//! code ported from JavaScript matches failures the same way, and the reason a
5//! given operation failed is looked up in the same place.
6
7use std::fmt;
8
9/// The result of any Web Bluetooth operation.
10pub type Result<T> = std::result::Result<T, Error>;
11
12/// Why a Web Bluetooth operation failed.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum Error {
15    /// No device matched, or the chooser declined to pick one. The spec throws
16    /// this when the user dismisses the device picker.
17    NotFound(String),
18
19    /// The operation is not permitted: a blocklisted UUID, or a service that
20    /// was never listed in `filters` / `optional_services`.
21    Security(String),
22
23    /// The object is no longer usable — the device disconnected, or the
24    /// peripheral re-advertised a different service set and invalidated every
25    /// handle into the old one.
26    InvalidState(String),
27
28    /// The GATT operation itself failed: the link dropped mid-request, the
29    /// peer rejected it, or `connect()` never completed.
30    Network(String),
31
32    /// The characteristic or descriptor does not support what was asked of it —
33    /// reading one with no `read` property, writing one with no `write`.
34    NotSupported(String),
35
36    /// A value was out of range, such as a write longer than the ATT MTU
37    /// allows.
38    InvalidModification(String),
39
40    /// Bluetooth is unavailable on this system, or this process is not
41    /// permitted to use it. Carries the underlying [`Availability`].
42    NotAvailable(Availability),
43
44    /// An operation exceeded its deadline.
45    Timeout(String),
46
47    /// The operation was cancelled — the future was dropped, or the adapter
48    /// reset underneath it.
49    Aborted(String),
50}
51
52/// Whether this process may use Bluetooth at all.
53///
54/// On Apple platforms this is the TCC verdict. Linux has no such gate, so the
55/// backend reports whether `bluetoothd` is reachable over D-Bus, which is the
56/// closest equivalent: a denial there is a policy decision too.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Authorization {
59    /// Never asked. On Apple platforms, also what a process with no
60    /// `NSBluetoothAlwaysUsageDescription` sees — and it is never prompted.
61    NotDetermined,
62    /// Refused by policy rather than by the user, such as an MDM profile.
63    Restricted,
64    /// The user said no.
65    Denied,
66    /// Permitted.
67    Allowed,
68}
69
70/// Why Bluetooth is not currently usable.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum Availability {
73    /// This machine has no Bluetooth LE radio, or its stack does not support it.
74    Unsupported,
75    /// The radio is powered off.
76    PoweredOff,
77    /// The process has no Bluetooth entitlement — on macOS and iOS this means
78    /// no `NSBluetoothAlwaysUsageDescription`, or the user declined. Note that
79    /// the system reports this *instead of* prompting when the process has no
80    /// usage description at all.
81    Unauthorized,
82    /// The adapter is resetting; try again shortly.
83    Resetting,
84    /// State is not yet known. `CBCentralManager` reports this until its first
85    /// `centralManagerDidUpdateState:`, which is why every entry point waits
86    /// for that callback before doing anything.
87    Unknown,
88}
89
90impl Error {
91    /// The `DOMException` name the Web Bluetooth spec uses for this failure.
92    pub fn name(&self) -> &'static str {
93        match self {
94            Self::NotFound(_) => "NotFoundError",
95            Self::Security(_) => "SecurityError",
96            Self::InvalidState(_) => "InvalidStateError",
97            Self::Network(_) => "NetworkError",
98            Self::NotSupported(_) => "NotSupportedError",
99            Self::InvalidModification(_) => "InvalidModificationError",
100            Self::NotAvailable(_) => "NotFoundError",
101            Self::Timeout(_) => "TimeoutError",
102            Self::Aborted(_) => "AbortError",
103        }
104    }
105}
106
107impl fmt::Display for Error {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        let detail = match self {
110            Self::NotFound(m)
111            | Self::Security(m)
112            | Self::InvalidState(m)
113            | Self::Network(m)
114            | Self::NotSupported(m)
115            | Self::InvalidModification(m)
116            | Self::Timeout(m)
117            | Self::Aborted(m) => m.clone(),
118            Self::NotAvailable(a) => a.to_string(),
119        };
120        write!(f, "{}: {detail}", self.name())
121    }
122}
123
124impl std::fmt::Display for Availability {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        let detail = match self {
127            Self::Unsupported => "this system has no Bluetooth LE support",
128            Self::PoweredOff => "Bluetooth is turned off",
129            Self::Unauthorized => {
130                "this process is not authorised to use Bluetooth — on Apple \
131                 platforms it needs NSBluetoothAlwaysUsageDescription in its \
132                 Info.plist"
133            }
134            Self::Resetting => "the Bluetooth adapter is resetting",
135            Self::Unknown => "Bluetooth state is not yet known",
136        };
137        f.write_str(detail)
138    }
139}
140
141impl std::error::Error for Error {}
142
143/// `availability()` hands an [`Availability`] back on its own rather than
144/// wrapped, because an unusable radio is a state rather than a failed call.
145/// That is worth keeping — and it should not also mean a caller cannot put it
146/// where every other failure goes. Without this, reporting one costs a manual
147/// translation into `anyhow`, `Box<dyn Error>` or a crate's own error type at
148/// each call site, which is exactly the boilerplate the trait exists to
149/// prevent.
150impl std::error::Error for Availability {}
151
152impl From<Availability> for Error {
153    /// The spec resolves a request against an unavailable radio as
154    /// `NotFoundError`, which is what [`Error::NotAvailable`] reports — so
155    /// `?` on an availability check inside a function returning [`Error`]
156    /// produces the same failure the operation itself would have.
157    fn from(availability: Availability) -> Self {
158        Self::NotAvailable(availability)
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    /// `availability()` hands an [`Availability`] back on its own, so it has
167    /// to read as a sentence without an [`Error`] around it. These messages
168    /// used to live inside `Error`'s `Display` and nowhere else.
169    #[test]
170    fn every_availability_explains_itself() {
171        let mut seen = std::collections::BTreeSet::new();
172        for a in [
173            Availability::Unsupported,
174            Availability::PoweredOff,
175            Availability::Unauthorized,
176            Availability::Resetting,
177            Availability::Unknown,
178        ] {
179            let said = a.to_string();
180            assert!(!said.is_empty(), "{a:?} says nothing");
181            // They are embedded — `Error` prints "{name}: {detail}", and the
182            // examples print "Bluetooth unavailable: {why}" — so a trailing
183            // full stop would land in the middle of somebody's sentence.
184            assert!(
185                !said.ends_with('.'),
186                "{a:?}: {said:?} ends a sentence it is inside of"
187            );
188            assert!(
189                seen.insert(said.clone()),
190                "{a:?} says the same as another: {said:?}"
191            );
192        }
193    }
194
195    /// The two must not drift apart now that one delegates to the other.
196    #[test]
197    fn an_unavailable_error_carries_the_same_explanation() {
198        let why = Availability::PoweredOff;
199        let wrapped = Error::NotAvailable(why).to_string();
200        assert!(
201            wrapped.contains(&why.to_string()),
202            "{wrapped:?} does not contain {:?}",
203            why.to_string()
204        );
205        // And still names the DOMException the specification defines.
206        assert!(wrapped.starts_with("NotFoundError"), "got {wrapped:?}");
207    }
208}