Skip to main content

camera_stream/
error.rs

1use core::fmt;
2
3#[cfg(target_os = "macos")]
4use objc2::rc::Retained;
5#[cfg(target_os = "macos")]
6use objc2::exception::Exception;
7#[cfg(target_os = "macos")]
8use objc2_foundation::NSError;
9
10/// Platform-specific error details.
11///
12/// On platforms that provide native error objects (e.g. `NSError` on macOS),
13/// the original object is preserved. Use [`Display`](fmt::Display) (or
14/// [`ToString::to_string`] when `alloc` is available) to obtain a
15/// human-readable description.
16#[derive(Debug)]
17#[non_exhaustive]
18pub enum PlatformError {
19    Message(&'static str),
20    #[cfg(target_os = "macos")]
21    NsError(Retained<NSError>),
22    #[cfg(target_os = "macos")]
23    ObjCException(Option<Retained<Exception>>),
24}
25
26impl fmt::Display for PlatformError {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            Self::Message(msg) => f.write_str(msg),
30            #[cfg(target_os = "macos")]
31            Self::NsError(e) => write!(f, "{e}"),
32            #[cfg(target_os = "macos")]
33            Self::ObjCException(Some(e)) => write!(f, "{e:?}"),
34            #[cfg(target_os = "macos")]
35            Self::ObjCException(None) => f.write_str("unknown Objective-C exception"),
36        }
37    }
38}
39
40impl core::error::Error for PlatformError {}
41
42/// Top-level crate error.
43#[derive(Debug)]
44#[non_exhaustive]
45pub enum Error {
46    DeviceNotFound,
47    UnsupportedFormat,
48    AlreadyStarted,
49    NotStarted,
50    Platform(PlatformError),
51}
52
53impl fmt::Display for Error {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match self {
56            Self::DeviceNotFound => f.write_str("no such device"),
57            Self::UnsupportedFormat => f.write_str("unsupported format"),
58            Self::AlreadyStarted => f.write_str("stream already started"),
59            Self::NotStarted => f.write_str("stream not started"),
60            Self::Platform(e) => write!(f, "platform error: {e}"),
61        }
62    }
63}
64
65impl core::error::Error for Error {
66    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
67        match self {
68            Self::Platform(e) => Some(e),
69            _ => None,
70        }
71    }
72}
73
74impl From<PlatformError> for Error {
75    fn from(e: PlatformError) -> Self {
76        Self::Platform(e)
77    }
78}