relayport_rs/
error.rs

1//! Errors returned by the library
2
3use std::net::AddrParseError;
4use tokio::sync::broadcast::error::RecvError;
5
6/// relayport-rs may return any of these errors.
7#[derive(Debug)]
8pub enum RelayPortError {
9    InternalCommunicationError(RecvError),
10    IoError(std::io::Error),
11    ParseAddrError(AddrParseError),
12    Unknown(String),
13}
14
15impl std::fmt::Display for RelayPortError {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        let msg = match self {
18            RelayPortError::IoError(e) => format!("io error: {e}"),
19            RelayPortError::ParseAddrError(e) => format!("unable to parse address: {e}"),
20            RelayPortError::Unknown(s) => format!("unknown error: {s}"),
21            RelayPortError::InternalCommunicationError(s) => {
22                format!("internal communication error: {s}")
23            }
24        };
25
26        write!(f, "{msg}")
27    }
28}
29
30impl std::error::Error for RelayPortError {
31    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
32        match self {
33            RelayPortError::IoError(e) => Some(e),
34            RelayPortError::ParseAddrError(e) => Some(e),
35            RelayPortError::Unknown(_) => None,
36            RelayPortError::InternalCommunicationError(e) => Some(e),
37        }
38    }
39}
40
41impl From<std::io::Error> for RelayPortError {
42    fn from(value: std::io::Error) -> Self {
43        Self::IoError(value)
44    }
45}
46
47impl From<RecvError> for RelayPortError {
48    fn from(value: RecvError) -> Self {
49        Self::InternalCommunicationError(value)
50    }
51}