#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RecvError {
Disconnected,
Lagged { skipped: usize },
}
impl std::fmt::Display for RecvError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RecvError::Disconnected => f.write_str("receive on a disconnected channel"),
RecvError::Lagged { skipped } => {
write!(f, "receiver lagged and missed {} messages", skipped)
}
}
}
}
impl std::error::Error for RecvError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TryRecvError {
Empty,
Disconnected,
Lagged { skipped: usize },
}
impl std::fmt::Display for TryRecvError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TryRecvError::Empty => f.write_str("channel is empty"),
TryRecvError::Disconnected => f.write_str("receive on a disconnected channel"),
TryRecvError::Lagged { skipped } => {
write!(f, "receiver lagged and missed {} messages", skipped)
}
}
}
}
impl std::error::Error for TryRecvError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SendError<T>(pub T);
impl<T: std::fmt::Debug> std::fmt::Display for SendError<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "send on a disconnected channel: {:?}", self.0)
}
}
impl<T: std::fmt::Debug + 'static> std::error::Error for SendError<T> {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn recv_error_display() {
assert_eq!(
RecvError::Disconnected.to_string(),
"receive on a disconnected channel"
);
assert_eq!(
RecvError::Lagged { skipped: 3 }.to_string(),
"receiver lagged and missed 3 messages"
);
}
#[test]
fn try_recv_error_display() {
assert_eq!(TryRecvError::Empty.to_string(), "channel is empty");
assert_eq!(
TryRecvError::Disconnected.to_string(),
"receive on a disconnected channel"
);
assert_eq!(
TryRecvError::Lagged { skipped: 5 }.to_string(),
"receiver lagged and missed 5 messages"
);
}
#[test]
fn send_error_display() {
let err = SendError(42i32);
assert_eq!(err.to_string(), "send on a disconnected channel: 42");
}
#[test]
fn errors_implement_std_error() {
fn assert_error<E: std::error::Error>() {}
assert_error::<RecvError>();
assert_error::<TryRecvError>();
assert_error::<SendError<i32>>();
}
}