kessel_audio/error.rs
1//! Errors.
2
3use std::fmt;
4
5/// What went wrong, as a stable code. The string forms
6/// ([`ErrorCode::as_str`]) are part of the public API.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8#[non_exhaustive]
9pub enum ErrorCode {
10 /// A device in use went away (unplugged, disabled, or its stream died).
11 DeviceLost,
12 /// The device is in use by something else, or temporarily unavailable.
13 DeviceBusy,
14 /// The OS refused access: the person declined or turned off microphone
15 /// access, policy forbids it, or (macOS) the app has no
16 /// `NSMicrophoneUsageDescription` so the OS can't ask. No input device is
17 /// open. The engine opens one by itself if access is granted later.
18 NoPermission,
19 /// No such device, or no device of that kind at all.
20 NoDevice,
21 /// The device can't run any configuration we can use.
22 UnsupportedConfig,
23 /// The configuration passed in is invalid.
24 InvalidConfig,
25 /// Anything else from the audio backend.
26 Backend,
27}
28
29impl ErrorCode {
30 /// The stable string form: `device_lost`, `device_busy`,
31 /// `no_permission`, `no_device`, `unsupported_config`, `invalid_config`
32 /// or `backend`.
33 pub fn as_str(&self) -> &'static str {
34 match self {
35 ErrorCode::DeviceLost => "device_lost",
36 ErrorCode::DeviceBusy => "device_busy",
37 ErrorCode::NoPermission => "no_permission",
38 ErrorCode::NoDevice => "no_device",
39 ErrorCode::UnsupportedConfig => "unsupported_config",
40 ErrorCode::InvalidConfig => "invalid_config",
41 ErrorCode::Backend => "backend",
42 }
43 }
44}
45
46impl fmt::Display for ErrorCode {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 f.write_str(self.as_str())
49 }
50}
51
52/// An error with its code and a human-readable detail.
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub struct AudioError {
55 /// The stable code.
56 pub code: ErrorCode,
57 /// Free text for logs; not stable.
58 pub detail: String,
59}
60
61impl AudioError {
62 pub(crate) fn new(code: ErrorCode, detail: impl Into<String>) -> Self {
63 AudioError {
64 code,
65 detail: detail.into(),
66 }
67 }
68}
69
70impl fmt::Display for AudioError {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 write!(f, "{}: {}", self.code, self.detail)
73 }
74}
75
76impl std::error::Error for AudioError {}