Skip to main content

rs_zero/rest/
error.rs

1use axum::response::IntoResponse;
2use thiserror::Error;
3
4use crate::rest::response::ApiResponse;
5
6/// Result type used by REST helpers.
7pub type RestResult<T> = Result<T, RestError>;
8
9/// Errors returned by REST middleware and handlers.
10#[derive(Debug, Error)]
11pub enum RestError {
12    #[error("unauthorized")]
13    Unauthorized,
14
15    #[error("request timed out")]
16    Timeout,
17
18    #[error("bad request: {0}")]
19    BadRequest(String),
20
21    #[error("internal error: {0}")]
22    Internal(String),
23}
24
25impl RestError {
26    /// Stable error code for uniform JSON responses.
27    pub fn code(&self) -> &'static str {
28        match self {
29            Self::Unauthorized => "UNAUTHORIZED",
30            Self::Timeout => "TIMEOUT",
31            Self::BadRequest(_) => "BAD_REQUEST",
32            Self::Internal(_) => "INTERNAL",
33        }
34    }
35}
36
37impl IntoResponse for RestError {
38    fn into_response(self) -> axum::response::Response {
39        ApiResponse::<()>::fail(self.code(), self.to_string()).into_response()
40    }
41}