Skip to main content

schedr_api/
error.rs

1//! Errors of the REST API, answered as JSON (`{"error": "..."}`).
2
3use 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/// Why a request failed.
14#[derive(Debug, thiserror::Error)]
15pub enum ApiError {
16    /// The request is malformed: a bad ID, body, query or version.
17    #[error("{0}")]
18    BadRequest(String),
19    /// No such DAG, run or command.
20    #[error("{0}")]
21    NotFound(String),
22    /// Not signed in (see [`crate::auth`]).
23    #[error("{0}")]
24    Unauthorized(String),
25    /// Refused whoever asks (a write from another site's page).
26    #[error("{0}")]
27    Forbidden(String),
28    /// Well-formed, but not to be done: an `Idempotency-Key` sent before with another command.
29    #[error("{0}")]
30    Unprocessable(String),
31    /// Something the request needs can't be reached now (a worker holding a log).
32    #[error("{0}")]
33    Unavailable(String),
34    /// The request's content is over what is taken (a posted event's data).
35    #[error("{0}")]
36    TooLarge(String),
37    /// It was there and was deleted for good (an output `[retention] outputs` removed).
38    #[error("{0}")]
39    Gone(String),
40    /// Something stored doesn't read (a run's DAG version a model change left behind): a 500
41    /// that says what, logged too (B89).
42    #[error("{0}")]
43    Unreadable(String),
44    /// The database failed (logged; the client gets a generic message).
45    #[error(transparent)]
46    Db(#[from] DbError),
47}
48
49impl ApiError {
50    /// The HTTP status for this error.
51    #[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}