reifydb_sub_server_http/
error.rs1use std::{error, fmt};
10
11use axum::{
12 Json,
13 http::StatusCode,
14 response::{IntoResponse, Response},
15};
16use reifydb_sub_server::{auth::AuthError, execute::ExecuteError};
17use reifydb_type::error::Diagnostic;
18use serde::Serialize;
19use tracing::{debug, error};
20
21#[derive(Debug, Serialize)]
23pub struct ErrorResponse {
24 pub error: String,
26 pub code: String,
28}
29
30impl ErrorResponse {
31 pub fn new(code: impl Into<String>, error: impl Into<String>) -> Self {
32 Self {
33 code: code.into(),
34 error: error.into(),
35 }
36 }
37}
38
39#[derive(Debug, Serialize)]
41pub struct DiagnosticResponse {
42 pub diagnostic: Diagnostic,
44}
45
46#[derive(Debug)]
48pub enum AppError {
49 Auth(AuthError),
51 Execute(ExecuteError),
53 BadRequest(String),
55 InvalidParams(String),
57 Internal(String),
59}
60
61impl From<AuthError> for AppError {
62 fn from(e: AuthError) -> Self {
63 AppError::Auth(e)
64 }
65}
66
67impl From<ExecuteError> for AppError {
68 fn from(e: ExecuteError) -> Self {
69 AppError::Execute(e)
70 }
71}
72
73impl fmt::Display for AppError {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 match self {
76 AppError::Auth(e) => write!(f, "Authentication error: {}", e),
77 AppError::Execute(e) => write!(f, "Execution error: {}", e),
78 AppError::BadRequest(msg) => write!(f, "Bad request: {}", msg),
79 AppError::InvalidParams(msg) => write!(f, "Invalid params: {}", msg),
80 AppError::Internal(msg) => write!(f, "Internal error: {}", msg),
81 }
82 }
83}
84
85impl error::Error for AppError {}
86
87impl IntoResponse for AppError {
88 fn into_response(self) -> Response {
89 if let AppError::Execute(ExecuteError::Engine {
91 diagnostic,
92 rql,
93 }) = self
94 {
95 debug!("Engine error: {}", diagnostic.message);
96 let mut diag = (*diagnostic).clone();
97 if diag.rql.is_none() && !rql.is_empty() {
98 diag.with_rql(rql);
99 }
100 let body = Json(DiagnosticResponse {
101 diagnostic: diag,
102 });
103 return (StatusCode::BAD_REQUEST, body).into_response();
104 }
105
106 let (status, code, message) = match &self {
107 AppError::Auth(AuthError::MissingCredentials) => {
108 (StatusCode::UNAUTHORIZED, "AUTH_REQUIRED", "Authentication required")
109 }
110 AppError::Auth(AuthError::InvalidToken) => {
111 (StatusCode::UNAUTHORIZED, "INVALID_TOKEN", "Invalid authentication token")
112 }
113 AppError::Auth(AuthError::Expired) => {
114 (StatusCode::UNAUTHORIZED, "TOKEN_EXPIRED", "Authentication token expired")
115 }
116 AppError::Auth(AuthError::InvalidHeader) => {
117 (StatusCode::BAD_REQUEST, "INVALID_HEADER", "Malformed authorization header")
118 }
119 AppError::Auth(AuthError::InsufficientPermissions) => {
120 (StatusCode::FORBIDDEN, "FORBIDDEN", "Insufficient permissions for this operation")
121 }
122 AppError::Execute(ExecuteError::Timeout) => {
123 (StatusCode::GATEWAY_TIMEOUT, "QUERY_TIMEOUT", "Query execution timed out")
124 }
125 AppError::Execute(ExecuteError::Cancelled) => {
126 (StatusCode::BAD_REQUEST, "QUERY_CANCELLED", "Query was cancelled")
127 }
128 AppError::Execute(ExecuteError::Disconnected) => {
129 error!("Query stream disconnected unexpectedly");
130 (StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "Internal server error")
131 }
132 AppError::Execute(ExecuteError::Rejected {
133 code,
134 message,
135 }) => {
136 let body = Json(ErrorResponse::new(code, message));
137 return (StatusCode::FORBIDDEN, body).into_response();
138 }
139 AppError::Execute(ExecuteError::Engine {
140 ..
141 }) => {
142 unreachable!()
144 }
145 AppError::BadRequest(msg) => {
146 let body = Json(ErrorResponse::new("BAD_REQUEST", msg.clone()));
147 return (StatusCode::BAD_REQUEST, body).into_response();
148 }
149 AppError::InvalidParams(msg) => {
150 let body = Json(ErrorResponse::new("INVALID_PARAMS", msg.clone()));
151 return (StatusCode::BAD_REQUEST, body).into_response();
152 }
153 AppError::Internal(msg) => {
154 error!("Internal error: {}", msg);
155 (StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "Internal server error")
156 }
157 };
158
159 let body = Json(ErrorResponse::new(code, message));
160 (status, body).into_response()
161 }
162}
163
164#[cfg(test)]
165pub mod tests {
166 use serde_json::to_string;
167
168 use super::*;
169
170 #[test]
171 fn test_error_response_serialization() {
172 let resp = ErrorResponse::new("TEST_CODE", "Test error message");
173 let json = to_string(&resp).unwrap();
174 assert!(json.contains("TEST_CODE"));
175 assert!(json.contains("Test error message"));
176 }
177
178 #[test]
179 fn test_app_error_display() {
180 let err = AppError::BadRequest("Invalid JSON".to_string());
181 assert_eq!(err.to_string(), "Bad request: Invalid JSON");
182 }
183}