Skip to main content

graphd_engine/
error.rs

1/// Typed errors for the graphd-engine API, aligned with Neo4j's error classification.
2///
3/// Each variant maps directly to a `Neo.{Classification}.{Category}.{Title}` code.
4/// Drivers use these codes for retry logic, error categorization, and user display.
5
6/// Neo4j-compatible error classification.
7///
8/// Variants follow Neo4j's three-tier hierarchy:
9/// - **ClientError** (4xx): Client sent a bad request — not retryable.
10/// - **DatabaseError** (5xx): Server failed — not retryable by default.
11/// - **TransientError**: Temporary condition — retryable.
12#[derive(Debug, Clone)]
13pub enum GraphdError {
14    /// `Neo.ClientError.Security.Forbidden` — operation blocked by policy.
15    /// Sandbox violations, disallowed CALL options, blocked statements.
16    Forbidden(String),
17
18    /// `Neo.ClientError.Statement.SyntaxError` — query parse or execution error.
19    /// Covers both Cypher syntax errors and runtime query failures from the engine.
20    SyntaxError(String),
21
22    /// `Neo.ClientError.Statement.TypeError` — invalid parameter types.
23    /// Unsupported number format, objects passed as params, non-object params value.
24    TypeError(String),
25
26    /// `Neo.TransientError.General.DatabaseUnavailable` — engine temporarily unavailable.
27    /// Semaphore/mutex closed, connection pool exhausted, shutdown in progress.
28    DatabaseUnavailable(String),
29
30    /// `Neo.DatabaseError.General.UnknownError` — internal server error.
31    /// Task panics, connection failures, database open failures, unexpected state.
32    DatabaseError(String),
33}
34
35impl std::fmt::Display for GraphdError {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        match self {
38            Self::Forbidden(msg)
39            | Self::SyntaxError(msg)
40            | Self::TypeError(msg)
41            | Self::DatabaseUnavailable(msg)
42            | Self::DatabaseError(msg) => write!(f, "{msg}"),
43        }
44    }
45}
46
47impl std::error::Error for GraphdError {}
48
49impl GraphdError {
50    /// Full Neo4j error code string (e.g. `Neo.ClientError.Security.Forbidden`).
51    pub fn neo4j_code(&self) -> &'static str {
52        match self {
53            Self::Forbidden(_) => "Neo.ClientError.Security.Forbidden",
54            Self::SyntaxError(_) => "Neo.ClientError.Statement.SyntaxError",
55            Self::TypeError(_) => "Neo.ClientError.Statement.TypeError",
56            Self::DatabaseUnavailable(_) => "Neo.TransientError.General.DatabaseUnavailable",
57            Self::DatabaseError(_) => "Neo.DatabaseError.General.UnknownError",
58        }
59    }
60
61    /// Whether this is a client error (bad request, not retryable).
62    pub fn is_client_error(&self) -> bool {
63        matches!(
64            self,
65            Self::Forbidden(_) | Self::SyntaxError(_) | Self::TypeError(_)
66        )
67    }
68
69    /// Whether the client should retry this request.
70    pub fn is_retryable(&self) -> bool {
71        matches!(self, Self::DatabaseUnavailable(_))
72    }
73
74    /// HTTP status code for this error.
75    pub fn http_status(&self) -> u16 {
76        match self {
77            Self::Forbidden(_) => 403,
78            Self::SyntaxError(_) | Self::TypeError(_) => 400,
79            Self::DatabaseUnavailable(_) => 503,
80            Self::DatabaseError(_) => 500,
81        }
82    }
83
84    /// The inner error message.
85    pub fn message(&self) -> &str {
86        match self {
87            Self::Forbidden(msg)
88            | Self::SyntaxError(msg)
89            | Self::TypeError(msg)
90            | Self::DatabaseUnavailable(msg)
91            | Self::DatabaseError(msg) => msg,
92        }
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn display_preserves_message() {
102        let err = GraphdError::SyntaxError("Binder exception: Table Person does not exist".into());
103        assert_eq!(
104            err.to_string(),
105            "Binder exception: Table Person does not exist"
106        );
107    }
108
109    #[test]
110    fn neo4j_codes_match_classification() {
111        assert_eq!(
112            GraphdError::Forbidden("x".into()).neo4j_code(),
113            "Neo.ClientError.Security.Forbidden"
114        );
115        assert_eq!(
116            GraphdError::SyntaxError("x".into()).neo4j_code(),
117            "Neo.ClientError.Statement.SyntaxError"
118        );
119        assert_eq!(
120            GraphdError::TypeError("x".into()).neo4j_code(),
121            "Neo.ClientError.Statement.TypeError"
122        );
123        assert_eq!(
124            GraphdError::DatabaseUnavailable("x".into()).neo4j_code(),
125            "Neo.TransientError.General.DatabaseUnavailable"
126        );
127        assert_eq!(
128            GraphdError::DatabaseError("x".into()).neo4j_code(),
129            "Neo.DatabaseError.General.UnknownError"
130        );
131    }
132
133    #[test]
134    fn client_errors() {
135        assert!(GraphdError::Forbidden("x".into()).is_client_error());
136        assert!(GraphdError::SyntaxError("x".into()).is_client_error());
137        assert!(GraphdError::TypeError("x".into()).is_client_error());
138        assert!(!GraphdError::DatabaseUnavailable("x".into()).is_client_error());
139        assert!(!GraphdError::DatabaseError("x".into()).is_client_error());
140    }
141
142    #[test]
143    fn retryable_only_transient() {
144        assert!(!GraphdError::Forbidden("x".into()).is_retryable());
145        assert!(!GraphdError::SyntaxError("x".into()).is_retryable());
146        assert!(!GraphdError::TypeError("x".into()).is_retryable());
147        assert!(GraphdError::DatabaseUnavailable("x".into()).is_retryable());
148        assert!(!GraphdError::DatabaseError("x".into()).is_retryable());
149    }
150
151    #[test]
152    fn http_status_codes() {
153        assert_eq!(GraphdError::Forbidden("x".into()).http_status(), 403);
154        assert_eq!(GraphdError::SyntaxError("x".into()).http_status(), 400);
155        assert_eq!(GraphdError::TypeError("x".into()).http_status(), 400);
156        assert_eq!(GraphdError::DatabaseUnavailable("x".into()).http_status(), 503);
157        assert_eq!(GraphdError::DatabaseError("x".into()).http_status(), 500);
158    }
159
160    #[test]
161    fn message_returns_inner_string() {
162        assert_eq!(GraphdError::Forbidden("blocked".into()).message(), "blocked");
163        assert_eq!(GraphdError::SyntaxError("bad query".into()).message(), "bad query");
164        assert_eq!(GraphdError::DatabaseError("oops".into()).message(), "oops");
165    }
166}