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 Internal,
47}
48
49impl ErrorCode {
50 #[must_use]
51 pub fn as_str(self) -> &'static str {
52 match self {
53 Self::NotFound => "not_found",
54 Self::BadRequest => "bad_request",
55 Self::Unauthenticated => "unauthenticated",
56 Self::Forbidden => "forbidden",
57 Self::PasswordRequired => "password_required",
58 Self::MethodNotAllowed => "method_not_allowed",
59 Self::Internal => "internal_error",
60 }
61 }
62
63 #[must_use]
64 pub fn status(self) -> StatusCode {
65 match self {
66 Self::NotFound => StatusCode::NOT_FOUND,
67 Self::BadRequest => StatusCode::BAD_REQUEST,
68 Self::Unauthenticated => StatusCode::UNAUTHORIZED,
69 Self::Forbidden | Self::PasswordRequired => StatusCode::FORBIDDEN,
70 Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
71 Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
72 }
73 }
74}
75
76#[derive(Debug, Clone)]
78pub struct ApiError {
79 pub code: ErrorCode,
80 pub message: String,
81}
82
83impl ApiError {
84 #[must_use]
85 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
86 Self {
87 code,
88 message: message.into(),
89 }
90 }
91
92 #[must_use]
96 pub fn not_found(what: &str) -> Self {
97 Self::new(ErrorCode::NotFound, format!("{what} not found"))
98 }
99
100 #[must_use]
101 pub fn bad_request(message: impl Into<String>) -> Self {
102 Self::new(ErrorCode::BadRequest, message)
103 }
104
105 #[must_use]
108 pub fn internal() -> Self {
109 Self::new(ErrorCode::Internal, "internal error")
110 }
111
112 #[must_use]
113 pub fn unauthenticated() -> Self {
114 Self::new(
115 ErrorCode::Unauthenticated,
116 "authentication required to view this page",
117 )
118 }
119
120 #[must_use]
121 pub fn forbidden() -> Self {
122 Self::new(ErrorCode::Forbidden, "you don't have access to this page")
123 }
124
125 #[must_use]
126 pub fn password_required() -> Self {
127 Self::new(
128 ErrorCode::PasswordRequired,
129 "this page is password-protected",
130 )
131 }
132}
133
134impl IntoResponse for ApiError {
135 fn into_response(self) -> Response {
136 (
137 self.code.status(),
138 Json(serde_json::json!({
139 "error": { "code": self.code.as_str(), "message": self.message }
140 })),
141 )
142 .into_response()
143 }
144}
145
146pub async fn method_not_allowed_json(
165 req: axum::extract::Request,
166 next: axum::middleware::Next,
167) -> Response {
168 let resp = next.run(req).await;
169 if resp.status() != StatusCode::METHOD_NOT_ALLOWED {
170 return resp;
171 }
172
173 let (parts, _) = resp.into_parts();
174 let mut out = ApiError::new(ErrorCode::MethodNotAllowed, "method not allowed").into_response();
175 for (name, value) in parts.headers {
176 let Some(name) = name else { continue };
177 if name == axum::http::header::CONTENT_LENGTH
179 || name == axum::http::header::CONTENT_TYPE
180 {
181 continue;
182 }
183 out.headers_mut().insert(name, value);
184 }
185 out
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191
192 #[test]
193 fn each_code_maps_to_one_status() {
194 assert_eq!(ErrorCode::NotFound.status(), StatusCode::NOT_FOUND);
195 assert_eq!(ErrorCode::BadRequest.status(), StatusCode::BAD_REQUEST);
196 assert_eq!(ErrorCode::Unauthenticated.status(), StatusCode::UNAUTHORIZED);
197 assert_eq!(ErrorCode::Forbidden.status(), StatusCode::FORBIDDEN);
198 assert_eq!(ErrorCode::PasswordRequired.status(), StatusCode::FORBIDDEN);
199 assert_eq!(
200 ErrorCode::Internal.status(),
201 StatusCode::INTERNAL_SERVER_ERROR,
202 );
203 }
204
205 #[test]
206 fn codes_are_stable_snake_case_identifiers() {
207 for (code, want) in [
209 (ErrorCode::NotFound, "not_found"),
210 (ErrorCode::BadRequest, "bad_request"),
211 (ErrorCode::Unauthenticated, "unauthenticated"),
212 (ErrorCode::Forbidden, "forbidden"),
213 (ErrorCode::PasswordRequired, "password_required"),
214 (ErrorCode::Internal, "internal_error"),
215 (ErrorCode::MethodNotAllowed, "method_not_allowed"),
216 ] {
217 assert_eq!(code.as_str(), want);
218 }
219 }
220
221 #[test]
222 fn not_found_reads_naturally_and_hides_the_reason() {
223 assert_eq!(ApiError::not_found("page").message, "page not found");
225 assert_eq!(ApiError::not_found("menu").message, "menu not found");
226 }
227}