File
Blob: firmware/crates/esp32-radio/src/error.rs
| 1 | //! Small diagnostic errors: no request bodies, credentials, or SDP in messages. |
| 2 | use std::fmt; |
| 3 | |
| 4 | #[derive(Debug, Clone, Copy)] |
| 5 | pub(crate) struct Error { |
| 6 | context: &'static str, |
| 7 | cause: Option<Cause>, |
| 8 | } |
| 9 | |
| 10 | #[derive(Debug, Clone, Copy)] |
| 11 | enum Cause { |
| 12 | Native(i32), |
| 13 | Music(radio_core::music::Error), |
| 14 | Transport(radio_webrtc::Error), |
| 15 | } |
| 16 | pub(crate) type Result<T> = std::result::Result<T, Error>; |
| 17 | |
| 18 | impl Error { |
| 19 | pub(crate) fn new(context: &'static str) -> Self { |
| 20 | Self { |
| 21 | context, |
| 22 | cause: None, |
| 23 | } |
| 24 | } |
| 25 | pub(crate) fn native(context: &'static str, code: i32) -> Self { |
| 26 | Self { |
| 27 | context, |
| 28 | cause: Some(Cause::Native(code)), |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | impl fmt::Display for Error { |
| 33 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 34 | f.write_str(self.context)?; |
| 35 | match self.cause { |
| 36 | Some(Cause::Native(code)) => write!(f, " (code {code})")?, |
| 37 | Some(Cause::Music(error)) => write!(f, ": {error}")?, |
| 38 | Some(Cause::Transport(error)) => write!(f, ": {error}")?, |
| 39 | None => {} |
| 40 | } |
| 41 | Ok(()) |
| 42 | } |
| 43 | } |
| 44 | impl std::error::Error for Error {} |
| 45 | impl From<&'static str> for Error { |
| 46 | fn from(value: &'static str) -> Self { |
| 47 | Self::new(value) |
| 48 | } |
| 49 | } |
| 50 | impl From<radio_core::music::Error> for Error { |
| 51 | fn from(value: radio_core::music::Error) -> Self { |
| 52 | Self { |
| 53 | context: "music unavailable", |
| 54 | cause: Some(Cause::Music(value)), |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | impl From<radio_webrtc::Error> for Error { |
| 59 | fn from(value: radio_webrtc::Error) -> Self { |
| 60 | Self { |
| 61 | context: "WebRTC transport", |
| 62 | cause: Some(Cause::Transport(value)), |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | pub(crate) fn check(code: i32, context: &'static str) -> Result<()> { |
| 67 | if code == 0 { |
| 68 | Ok(()) |
| 69 | } else { |
| 70 | Err(Error::native(context, code)) |
| 71 | } |
| 72 | } |