1use axum::Json;
4use axum::http::StatusCode;
5use axum::response::{IntoResponse, Response};
6use schedr_db::DbError;
7
8use crate::views::ErrorBody;
9
10#[cfg(test)]
11mod tests;
12
13#[derive(Debug, thiserror::Error)]
15pub enum ApiError {
16 #[error("{0}")]
18 BadRequest(String),
19 #[error("{0}")]
21 NotFound(String),
22 #[error("{0}")]
24 Unauthorized(String),
25 #[error("{0}")]
27 Forbidden(String),
28 #[error("{0}")]
30 Unprocessable(String),
31 #[error("{0}")]
33 Unavailable(String),
34 #[error("{0}")]
36 TooLarge(String),
37 #[error("{0}")]
39 Gone(String),
40 #[error("{0}")]
43 Unreadable(String),
44 #[error(transparent)]
46 Db(#[from] DbError),
47}
48
49impl ApiError {
50 #[must_use]
52 pub const fn status(&self) -> StatusCode {
53 match self {
54 Self::BadRequest(_) => StatusCode::BAD_REQUEST,
55 Self::NotFound(_) => StatusCode::NOT_FOUND,
56 Self::Unauthorized(_) => StatusCode::UNAUTHORIZED,
57 Self::Forbidden(_) => StatusCode::FORBIDDEN,
58 Self::Unprocessable(_) => StatusCode::UNPROCESSABLE_ENTITY,
59 Self::Unavailable(_) => StatusCode::SERVICE_UNAVAILABLE,
60 Self::TooLarge(_) => StatusCode::PAYLOAD_TOO_LARGE,
61 Self::Gone(_) => StatusCode::GONE,
62 Self::Unreadable(_) | Self::Db(_) => StatusCode::INTERNAL_SERVER_ERROR,
63 }
64 }
65}
66
67impl IntoResponse for ApiError {
68 fn into_response(self) -> Response {
69 let status = self.status();
70 let error = match &self {
71 Self::Db(error) => {
72 tracing::error!(%error, "API request failed");
73 "the database failed; see the webserver's log".to_owned()
74 }
75 Self::Unreadable(what) => what.clone(),
76 _ => self.to_string(),
77 };
78 (status, Json(ErrorBody { error })).into_response()
79 }
80}