Skip to main content

aurelin_framework/http/
errors.rs

1//! Explicit, safe JSON application error responses.
2use axum::{
3    Json,
4    http::StatusCode,
5    response::{IntoResponse, Response},
6};
7use serde::Serialize;
8use std::{error::Error, fmt};
9
10/// Public HTTP failures. Internal sources remain available through `Error::source`.
11#[derive(Debug)]
12pub enum AppError {
13    NotFound,
14    MethodNotAllowed,
15    Unauthorized,
16    Forbidden,
17    Internal(Box<dyn Error + Send + Sync>),
18}
19
20impl fmt::Display for AppError {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        f.write_str(self.public().2)
23    }
24}
25
26impl Error for AppError {
27    fn source(&self) -> Option<&(dyn Error + 'static)> {
28        match self {
29            Self::Internal(source) => Some(source.as_ref()),
30            _ => None,
31        }
32    }
33}
34
35impl AppError {
36    fn public(&self) -> (StatusCode, &'static str, &'static str) {
37        match self {
38            Self::NotFound => (StatusCode::NOT_FOUND, "not_found", "Not found."),
39            Self::MethodNotAllowed => (StatusCode::METHOD_NOT_ALLOWED, "method_not_allowed", "Method not allowed."),
40            Self::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized", "Authentication required."),
41            Self::Forbidden => (StatusCode::FORBIDDEN, "forbidden", "Forbidden."),
42            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error", "Server error."),
43        }
44    }
45}
46
47#[derive(Serialize)]
48struct Body {
49    code: &'static str,
50    message: &'static str,
51}
52
53impl IntoResponse for AppError {
54    fn into_response(self) -> Response {
55        let (status, code, message) = self.public();
56        (status, Json(Body { code, message })).into_response()
57    }
58}