1use axum::Json;
16use axum::http::StatusCode;
17use axum::response::{IntoResponse, Response};
18use std::collections::HashMap;
19use tracing::error;
20
21#[derive(Debug)]
23pub enum RavelError {
24 NotFound(String),
26 BadRequest(String),
28 Unauthorized(String),
30 Forbidden(String),
32 ValidationError(HashMap<String, Vec<String>>),
34 Internal(anyhow::Error),
36}
37
38impl RavelError {
39 pub fn not_found(msg: impl Into<String>) -> Self {
41 Self::NotFound(msg.into())
42 }
43
44 pub fn bad_request(msg: impl Into<String>) -> Self {
46 Self::BadRequest(msg.into())
47 }
48
49 pub fn unauthorized(msg: impl Into<String>) -> Self {
51 Self::Unauthorized(msg.into())
52 }
53
54 pub fn forbidden(msg: impl Into<String>) -> Self {
56 Self::Forbidden(msg.into())
57 }
58
59 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#[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}