rs_mongo_stream/
error.rs

1//! Error types for MongoDB change stream operations.
2//!
3//! This module provides a unified error type for all operations in the crate.
4
5use std::{error::Error, fmt};
6
7/// Represents errors that can occur when working with MongoDB change streams.
8///
9/// This type wraps the various error types that might be encountered when
10/// interacting with MongoDB, providing a unified error handling approach.
11#[derive(Debug)]
12pub struct MongoStreamError {
13    /// The error message
14    message: String,
15}
16
17impl MongoStreamError {
18    /// Creates a new error with the given message.
19    ///
20    /// # Arguments
21    ///
22    /// * `message` - A string describing the error.
23    ///
24    /// # Returns
25    ///
26    /// A new `MongoStreamError` instance.
27    pub fn new(message: impl Into<String>) -> Self {
28        Self {
29            message: message.into(),
30        }
31    }
32}
33
34// Standard Error trait implementation
35impl Error for MongoStreamError {}
36
37// Display implementation for human-readable error messages
38impl fmt::Display for MongoStreamError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        write!(f, "MongoStream error: {}", self.message)
41    }
42}
43
44// Conversion from MongoDB's error type
45impl From<mongodb::error::Error> for MongoStreamError {
46    fn from(error: mongodb::error::Error) -> Self {
47        Self {
48            message: error.to_string(),
49        }
50    }
51}
52
53// Conversion from other error types that might be encountered
54impl From<tokio::sync::mpsc::error::SendError<()>> for MongoStreamError {
55    fn from(error: tokio::sync::mpsc::error::SendError<()>) -> Self {
56        Self {
57            message: format!("Failed to send close signal: {}", error),
58        }
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65    use tokio::sync::mpsc::error::SendError;
66
67    #[test]
68    fn test_new_error() {
69        let err = MongoStreamError::new("test error");
70        assert_eq!(err.message, "test error");
71    }
72
73    #[test]
74    fn test_display_formatting() {
75        let err = MongoStreamError::new("test error");
76        assert_eq!(format!("{}", err), "MongoStream error: test error");
77    }
78
79    #[test]
80    fn test_error_trait() {
81        let err = MongoStreamError::new("test error");
82        assert!(err.source().is_none());
83    }
84
85    #[test]
86    fn test_from_send_error() {
87        let send_err = SendError(());
88        let err: MongoStreamError = send_err.into();
89        assert!(err.message.contains("Failed to send close signal"));
90    }
91}