Skip to main content

rustauth_core/plugin/
error.rs

1//! Plugin error code registry types.
2
3use crate::error::RustAuthError;
4use crate::error_codes::ErrorCode;
5
6/// Error code contributed by a plugin.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct PluginErrorCode {
9    pub code: String,
10    pub message: String,
11}
12
13impl PluginErrorCode {
14    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
15        Self {
16            code: code.into(),
17            message: message.into(),
18        }
19    }
20
21    pub fn validate(&self) -> Result<(), RustAuthError> {
22        if self.code.is_empty()
23            || !self
24                .code
25                .bytes()
26                .all(|byte| byte == b'_' || byte.is_ascii_uppercase())
27        {
28            return Err(RustAuthError::InvalidConfig(format!(
29                "plugin error code `{}` must use upper snake case",
30                self.code
31            )));
32        }
33        Ok(())
34    }
35}
36
37impl ErrorCode for PluginErrorCode {
38    fn as_str(&self) -> &str {
39        &self.code
40    }
41
42    fn message(&self) -> &str {
43        &self.message
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50    use crate::error_codes::ErrorCode;
51
52    fn assert_error_code(code: impl ErrorCode, expected_code: &str, expected_message: &str) {
53        assert_eq!(code.as_str(), expected_code);
54        assert_eq!(code.message(), expected_message);
55    }
56
57    #[test]
58    fn plugin_error_code_implements_error_code_trait() {
59        assert_error_code(
60            PluginErrorCode::new("PLUGIN_FAILURE", "Plugin failure"),
61            "PLUGIN_FAILURE",
62            "Plugin failure",
63        );
64    }
65}