rustango_cms/api/
error.rs1use axum::http::StatusCode;
21use axum::response::{IntoResponse, Response};
22use axum::Json;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum ErrorCode {
30 NotFound,
33 BadRequest,
36 Unauthenticated,
38 Forbidden,
40 PasswordRequired,
42 MethodNotAllowed,
45 RateLimited,
47 Unavailable,
49 Internal,
51}
52
53impl ErrorCode {
54 #[must_use]
55 pub fn as_str(self) -> &'static str {
56 match self {
57 Self::NotFound => "not_found",
58 Self::BadRequest => "bad_request",
59 Self::Unauthenticated => "unauthenticated",
60 Self::Forbidden => "forbidden",
61 Self::PasswordRequired => "password_required",
62 Self::MethodNotAllowed => "method_not_allowed",
63 Self::RateLimited => "rate_limited",
64 Self::Unavailable => "unavailable",
65 Self::Internal => "internal_error",
66 }
67 }
68
69 #[must_use]
70 pub fn status(self) -> StatusCode {
71 match self {
72 Self::NotFound => StatusCode::NOT_FOUND,
73 Self::BadRequest => StatusCode::BAD_REQUEST,
74 Self::Unauthenticated => StatusCode::UNAUTHORIZED,
75 Self::Forbidden | Self::PasswordRequired => StatusCode::FORBIDDEN,
76 Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
77 Self::RateLimited => StatusCode::TOO_MANY_REQUESTS,
78 Self::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
79 Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
80 }
81 }
82}
83
84#[derive(Debug, Clone)]
86pub struct ApiError {
87 pub code: ErrorCode,
88 pub message: String,
89}
90
91impl ApiError {
92 #[must_use]
93 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
94 Self {
95 code,
96 message: message.into(),
97 }
98 }
99
100 #[must_use]
104 pub fn not_found(what: &str) -> Self {
105 Self::new(ErrorCode::NotFound, format!("{what} not found"))
106 }
107
108 #[must_use]
109 pub fn bad_request(message: impl Into<String>) -> Self {
110 Self::new(ErrorCode::BadRequest, message)
111 }
112
113 #[must_use]
116 pub fn internal() -> Self {
117 Self::new(ErrorCode::Internal, "internal error")
118 }
119
120 #[must_use]
121 pub fn unauthenticated() -> Self {
122 Self::new(
123 ErrorCode::Unauthenticated,
124 "authentication required to view this page",
125 )
126 }
127
128 #[must_use]
129 pub fn forbidden() -> Self {
130 Self::new(ErrorCode::Forbidden, "you don't have access to this page")
131 }
132
133 #[must_use]
134 pub fn password_required() -> Self {
135 Self::new(
136 ErrorCode::PasswordRequired,
137 "this page is password-protected",
138 )
139 }
140}
141
142impl IntoResponse for ApiError {
143 fn into_response(self) -> Response {
144 (
145 self.code.status(),
146 Json(serde_json::json!({
147 "error": { "code": self.code.as_str(), "message": self.message }
148 })),
149 )
150 .into_response()
151 }
152}
153
154pub async fn method_not_allowed_json(
173 req: axum::extract::Request,
174 next: axum::middleware::Next,
175) -> Response {
176 let resp = next.run(req).await;
177 if resp.status() != StatusCode::METHOD_NOT_ALLOWED {
178 return resp;
179 }
180
181 let (parts, _) = resp.into_parts();
182 let mut out = ApiError::new(ErrorCode::MethodNotAllowed, "method not allowed").into_response();
183 for (name, value) in parts.headers {
184 let Some(name) = name else { continue };
185 if name == axum::http::header::CONTENT_LENGTH
187 || name == axum::http::header::CONTENT_TYPE
188 {
189 continue;
190 }
191 out.headers_mut().insert(name, value);
192 }
193 out
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199
200 #[test]
201 fn each_code_maps_to_one_status() {
202 assert_eq!(ErrorCode::NotFound.status(), StatusCode::NOT_FOUND);
203 assert_eq!(ErrorCode::BadRequest.status(), StatusCode::BAD_REQUEST);
204 assert_eq!(ErrorCode::Unauthenticated.status(), StatusCode::UNAUTHORIZED);
205 assert_eq!(ErrorCode::Forbidden.status(), StatusCode::FORBIDDEN);
206 assert_eq!(ErrorCode::PasswordRequired.status(), StatusCode::FORBIDDEN);
207 assert_eq!(ErrorCode::RateLimited.status(), StatusCode::TOO_MANY_REQUESTS);
208 assert_eq!(ErrorCode::Unavailable.status(), StatusCode::SERVICE_UNAVAILABLE);
209 assert_eq!(
210 ErrorCode::Internal.status(),
211 StatusCode::INTERNAL_SERVER_ERROR,
212 );
213 }
214
215 #[test]
216 fn codes_are_stable_snake_case_identifiers() {
217 for (code, want) in [
219 (ErrorCode::NotFound, "not_found"),
220 (ErrorCode::BadRequest, "bad_request"),
221 (ErrorCode::Unauthenticated, "unauthenticated"),
222 (ErrorCode::Forbidden, "forbidden"),
223 (ErrorCode::PasswordRequired, "password_required"),
224 (ErrorCode::Internal, "internal_error"),
225 (ErrorCode::MethodNotAllowed, "method_not_allowed"),
226 (ErrorCode::RateLimited, "rate_limited"),
227 (ErrorCode::Unavailable, "unavailable"),
228 ] {
229 assert_eq!(code.as_str(), want);
230 }
231 }
232
233 #[test]
234 fn not_found_reads_naturally_and_hides_the_reason() {
235 assert_eq!(ApiError::not_found("page").message, "page not found");
237 assert_eq!(ApiError::not_found("menu").message, "menu not found");
238 }
239}