Skip to main content

openlark_webhook/common/
error.rs

1//! Webhook 模块错误类型。
2
3use thiserror::Error;
4
5/// Webhook 调用过程中可能出现的错误。
6#[derive(Debug, Error)]
7pub enum WebhookError {
8    /// HTTP 请求发送或服务端返回失败。
9    #[error("HTTP error: {0}")]
10    Http(String),
11
12    /// 请求或响应 JSON 序列化失败。
13    #[error("Serialization error: {0}")]
14    Serialization(#[from] serde_json::Error),
15
16    /// 签名校验失败。
17    #[error("Invalid signature")]
18    InvalidSignature,
19
20    /// 缺少必填字段。
21    #[error("Missing required field: {0}")]
22    MissingField(String),
23}
24
25impl PartialEq for WebhookError {
26    fn eq(&self, other: &Self) -> bool {
27        match (self, other) {
28            (Self::Http(a), Self::Http(b)) => a == b,
29            (Self::Serialization(_), Self::Serialization(_)) => true,
30            (Self::InvalidSignature, Self::InvalidSignature) => true,
31            (Self::MissingField(a), Self::MissingField(b)) => a == b,
32            _ => false,
33        }
34    }
35}
36
37/// Webhook 模块统一结果类型。
38pub type Result<T> = std::result::Result<T, WebhookError>;
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    #[test]
45    fn test_webhook_error_display_http() {
46        let err = WebhookError::Http("connection refused".to_string());
47        assert_eq!(err.to_string(), "HTTP error: connection refused");
48    }
49
50    #[test]
51    fn test_webhook_error_display_serialization() {
52        let json_err = serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
53        let err = WebhookError::Serialization(json_err);
54        assert!(err.to_string().starts_with("Serialization error:"));
55    }
56
57    #[test]
58    fn test_webhook_error_display_invalid_signature() {
59        let err = WebhookError::InvalidSignature;
60        assert_eq!(err.to_string(), "Invalid signature");
61    }
62
63    #[test]
64    fn test_webhook_error_display_missing_field() {
65        let err = WebhookError::MissingField("webhook_url".to_string());
66        assert_eq!(err.to_string(), "Missing required field: webhook_url");
67    }
68
69    #[test]
70    fn test_webhook_error_debug() {
71        let err = WebhookError::InvalidSignature;
72        let debug_str = format!("{err:?}");
73        assert!(debug_str.contains("InvalidSignature"));
74    }
75
76    #[test]
77    fn test_result_type() {
78        let ok_result: Result<i32> = Ok(42);
79        assert_eq!(ok_result, Ok(42));
80
81        let err_result: Result<i32> = Err(WebhookError::InvalidSignature);
82        assert!(err_result.is_err());
83    }
84}