twyg/
error.rs

1//! Error types for the twyg logging library.
2//!
3//! This module provides custom error types for twyg operations using the
4//! [`thiserror`](https://docs.rs/thiserror) crate for ergonomic error handling.
5//!
6//! # Error Types
7//!
8//! - [`TwygError`] - The main error type for all twyg operations
9//! - [`Result<T>`] - Type alias for `std::result::Result<T, TwygError>`
10//!
11//! # Examples
12//!
13//! ```
14//! use twyg::{OptsBuilder, LogLevel};
15//!
16//! // Invalid time format returns ConfigError
17//! let result = OptsBuilder::new()
18//!     .time_format("%invalid")
19//!     .build();
20//! assert!(result.is_err());
21//! ```
22
23use std::io;
24
25use thiserror::Error;
26
27/// Custom error type for twyg operations.
28#[derive(Debug, Error)]
29pub enum TwygError {
30    /// Invalid time format string provided.
31    #[error("invalid time format '{format}': {source}")]
32    InvalidTimeFormat {
33        format: String,
34        #[source]
35        source: io::Error,
36    },
37
38    /// Failed to initialize the logger.
39    #[error("failed to initialize logger")]
40    InitError,
41
42    /// Failed to open or write to log file.
43    #[error("failed to open log file: {0}")]
44    FileError(#[from] io::Error),
45
46    /// Configuration error.
47    #[error("configuration error: {0}")]
48    ConfigError(String),
49}
50
51/// Result type alias using TwygError.
52pub type Result<T> = std::result::Result<T, TwygError>;
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn test_error_display() {
60        let err = TwygError::ConfigError("test error".to_string());
61        assert_eq!(err.to_string(), "configuration error: test error");
62    }
63
64    #[test]
65    fn test_file_error() {
66        let io_err = io::Error::new(io::ErrorKind::NotFound, "file not found");
67        let err = TwygError::FileError(io_err);
68        assert!(err.to_string().contains("failed to open log file"));
69    }
70
71    #[test]
72    fn test_invalid_time_format() {
73        let io_err = io::Error::new(io::ErrorKind::InvalidInput, "bad format");
74        let err = TwygError::InvalidTimeFormat {
75            format: "%Z".to_string(),
76            source: io_err,
77        };
78        assert!(err.to_string().contains("invalid time format"));
79        assert!(err.to_string().contains("%Z"));
80    }
81}