Skip to main content

mentedb_server/
error.rs

1//! API error types with automatic HTTP status code mapping.
2
3use axum::http::StatusCode;
4use axum::response::{IntoResponse, Response};
5use serde_json::json;
6
7/// Unified API error type.
8#[derive(Debug)]
9#[allow(dead_code)]
10pub enum ApiError {
11    BadRequest(String),
12    NotFound(String),
13    Unauthorized(String),
14    Forbidden(String),
15    RateLimited,
16    Internal(String),
17    ServiceUnavailable(String),
18}
19
20impl std::fmt::Display for ApiError {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        match self {
23            Self::BadRequest(msg) => write!(f, "bad request: {msg}"),
24            Self::NotFound(msg) => write!(f, "not found: {msg}"),
25            Self::Unauthorized(msg) => write!(f, "unauthorized: {msg}"),
26            Self::Forbidden(msg) => write!(f, "forbidden: {msg}"),
27            Self::RateLimited => write!(f, "rate limited"),
28            Self::Internal(msg) => write!(f, "internal error: {msg}"),
29            Self::ServiceUnavailable(msg) => write!(f, "service unavailable: {msg}"),
30        }
31    }
32}
33
34impl IntoResponse for ApiError {
35    fn into_response(self) -> Response {
36        let (status, message) = match &self {
37            Self::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
38            Self::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()),
39            Self::Unauthorized(msg) => (StatusCode::UNAUTHORIZED, msg.clone()),
40            Self::Forbidden(msg) => (StatusCode::FORBIDDEN, msg.clone()),
41            Self::RateLimited => (
42                StatusCode::TOO_MANY_REQUESTS,
43                "too many requests".to_string(),
44            ),
45            Self::Internal(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
46            Self::ServiceUnavailable(msg) => (StatusCode::SERVICE_UNAVAILABLE, msg.clone()),
47        };
48
49        let body = json!({ "error": message });
50        (status, axum::Json(body)).into_response()
51    }
52}