Skip to main content

ravel_http/
error.rs

1//! Unified error type for the Ravel HTTP layer.
2//!
3//! [`RavelError`] implements [`axum::response::IntoResponse`] so handlers can
4//! return `Result<T, RavelError>` and use `?` propagation:
5//!
6//! ```rust,ignore
7//! use ravel_http::error::RavelError;
8//!
9//! async fn show_user(id: u32) -> Result<impl IntoResponse, RavelError> {
10//!     let user = find_user(id).ok_or(RavelError::not_found("User not found"))?;
11//!     Ok(Json(user))
12//! }
13//! ```
14
15use axum::Json;
16use axum::http::StatusCode;
17use axum::response::{IntoResponse, Response};
18use std::collections::HashMap;
19use tracing::error;
20
21/// Unified error type that maps to HTTP responses.
22#[derive(Debug)]
23pub enum RavelError {
24    /// 404 — resource not found.
25    NotFound(String),
26    /// 400 — malformed request.
27    BadRequest(String),
28    /// 401 — missing or invalid authentication.
29    Unauthorized(String),
30    /// 403 — authenticated but not permitted.
31    Forbidden(String),
32    /// 422 — validation failed.  Keys are field names, values are error lists.
33    ValidationError(HashMap<String, Vec<String>>),
34    /// 500 — unexpected internal error.
35    Internal(anyhow::Error),
36}
37
38impl RavelError {
39    /// Create a 404 Not Found error.
40    pub fn not_found(msg: impl Into<String>) -> Self {
41        Self::NotFound(msg.into())
42    }
43
44    /// Create a 400 Bad Request error.
45    pub fn bad_request(msg: impl Into<String>) -> Self {
46        Self::BadRequest(msg.into())
47    }
48
49    /// Create a 401 Unauthorized error.
50    pub fn unauthorized(msg: impl Into<String>) -> Self {
51        Self::Unauthorized(msg.into())
52    }
53
54    /// Create a 403 Forbidden error.
55    pub fn forbidden(msg: impl Into<String>) -> Self {
56        Self::Forbidden(msg.into())
57    }
58
59    /// Create a 422 Validation Error.
60    pub fn validation_error(errors: HashMap<String, Vec<String>>) -> Self {
61        Self::ValidationError(errors)
62    }
63}
64
65impl IntoResponse for RavelError {
66    fn into_response(self) -> Response {
67        match self {
68            Self::NotFound(msg) => (
69                StatusCode::NOT_FOUND,
70                Json(serde_json::json!({"message": msg, "status": 404})),
71            )
72                .into_response(),
73            Self::BadRequest(msg) => (
74                StatusCode::BAD_REQUEST,
75                Json(serde_json::json!({"message": msg, "status": 400})),
76            )
77                .into_response(),
78            Self::Unauthorized(msg) => (
79                StatusCode::UNAUTHORIZED,
80                Json(serde_json::json!({"message": msg, "status": 401})),
81            )
82                .into_response(),
83            Self::Forbidden(msg) => (
84                StatusCode::FORBIDDEN,
85                Json(serde_json::json!({"message": msg, "status": 403})),
86            )
87                .into_response(),
88            Self::ValidationError(errors) => (
89                StatusCode::UNPROCESSABLE_ENTITY,
90                Json(serde_json::json!({
91                    "message": "Validation failed",
92                    "errors": errors,
93                    "status": 422,
94                })),
95            )
96                .into_response(),
97            Self::Internal(e) => {
98                error!("Internal error: {e:?}");
99                (
100                    StatusCode::INTERNAL_SERVER_ERROR,
101                    Json(serde_json::json!({
102                        "message": "Internal server error",
103                        "status": 500,
104                    })),
105                )
106                    .into_response()
107            }
108        }
109    }
110}
111
112impl From<anyhow::Error> for RavelError {
113    fn from(e: anyhow::Error) -> Self {
114        Self::Internal(e)
115    }
116}
117
118// ── Tests ────────────────────────────────────────────────────────────────
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    fn extract_body(resp: Response) -> serde_json::Value {
125        let rt = tokio::runtime::Runtime::new().unwrap();
126        let body_bytes = rt
127            .block_on(axum::body::to_bytes(resp.into_body(), 1024))
128            .unwrap();
129        serde_json::from_slice(&body_bytes).unwrap()
130    }
131
132    #[test]
133    fn test_not_found_response() {
134        let resp = RavelError::not_found("User 42 not found").into_response();
135        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
136        let body = extract_body(resp);
137        assert_eq!(body["message"], "User 42 not found");
138        assert_eq!(body["status"], 404);
139    }
140
141    #[test]
142    fn test_bad_request_response() {
143        let resp = RavelError::bad_request("Missing field").into_response();
144        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
145        let body = extract_body(resp);
146        assert_eq!(body["status"], 400);
147    }
148
149    #[test]
150    fn test_unauthorized_response() {
151        let resp = RavelError::unauthorized("Invalid token").into_response();
152        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
153        let body = extract_body(resp);
154        assert_eq!(body["status"], 401);
155    }
156
157    #[test]
158    fn test_forbidden_response() {
159        let resp = RavelError::forbidden("Access denied").into_response();
160        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
161        let body = extract_body(resp);
162        assert_eq!(body["status"], 403);
163    }
164
165    #[test]
166    fn test_validation_error_response() {
167        let mut errors = HashMap::new();
168        errors.insert("email".into(), vec!["The email field is required.".into()]);
169        let resp = RavelError::validation_error(errors).into_response();
170        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
171        let body = extract_body(resp);
172        assert_eq!(body["status"], 422);
173        assert!(
174            body["errors"]["email"][0]
175                .as_str()
176                .unwrap()
177                .contains("required")
178        );
179    }
180
181    #[test]
182    fn test_internal_response() {
183        let err = RavelError::Internal(anyhow::anyhow!("db connection lost"));
184        let resp = err.into_response();
185        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
186        let body = extract_body(resp);
187        assert_eq!(body["status"], 500);
188        assert_eq!(body["message"], "Internal server error");
189    }
190
191    #[test]
192    fn test_from_anyhow() {
193        let err: RavelError = anyhow::anyhow!("something broke").into();
194        let resp = err.into_response();
195        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
196    }
197}