apikit/
reject.rs

1//! Commonly used rejections and recovery procedures.
2use axum::http::StatusCode;
3
4use axum::response::{IntoResponse, Response};
5
6use crate::reply;
7use serde::Serialize;
8
9const MESSAGE_NOT_FOUND: &str = "not found";
10const MESSAGE_FORBIDDEN: &str = "forbidden";
11const MESSAGE_INTERNAL_SERVER_ERROR: &str = "internal server error";
12
13#[derive(Serialize)]
14#[serde(untagged)]
15pub enum HTTPError {
16    BadRequest { error: String },
17    Forbidden,
18    NotFound,
19    InternalServerError { error: String },
20}
21
22impl HTTPError {
23    pub fn bad_request<S: ToString>(s: S) -> Self {
24        Self::BadRequest {
25            error: s.to_string(),
26        }
27    }
28
29    pub fn internal_server_error<S: ToString>(s: S) -> Self {
30        Self::InternalServerError {
31            error: s.to_string(),
32        }
33    }
34}
35
36impl IntoResponse for HTTPError {
37    fn into_response(self) -> Response {
38        match self {
39            Self::BadRequest { error } => reply::error(error, StatusCode::BAD_REQUEST),
40            Self::Forbidden => reply::error(MESSAGE_FORBIDDEN, StatusCode::FORBIDDEN),
41            Self::NotFound => reply::error(MESSAGE_NOT_FOUND, StatusCode::NOT_FOUND),
42            Self::InternalServerError { ref error } => {
43                tracing::error!("{error}");
44                reply::error(
45                    MESSAGE_INTERNAL_SERVER_ERROR,
46                    StatusCode::INTERNAL_SERVER_ERROR,
47                )
48            }
49        }
50    }
51}