aboutsummaryrefslogtreecommitdiff
path: root/src/errors.rs
blob: 23ad8fac1a311c4299a5c8e7e727b8c073b217e7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
use axum::body;
use axum::response::{IntoResponse, Response, Html};
use hyper::StatusCode;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum ServiceError {
    #[error("No config file")]
    MissingConfig,
    #[error("Invalid config file: {0}")]
    InvalidConfig(#[from] toml::de::Error),
    #[error("Not Authorized")]
    NotAuthorized,
    #[error("Not Found")]
    NotFound,
    #[error("Axum: {0}")]
    Axum(#[from] axum::Error),
    #[error("SQL: {0}")]
    Sql(#[from] sqlx::Error),
    #[error("Bcrypt: {0}")]
    Bcrypt(#[from] bcrypt::BcryptError),
}

pub type StringResult<T = String> = Result<T, ServiceError>;
pub type HtmlResult<T = Html<String>> = Result<T, ServiceError>;
pub type JsonResult<T> = Result<T, ServiceError>;

impl IntoResponse for ServiceError {
    fn into_response(self) -> axum::response::Response {
        let body = body::boxed(body::Full::from(self.to_string()));

        let status = match self {
            ServiceError::NotFound => StatusCode::NOT_FOUND,
            ServiceError::NotAuthorized => StatusCode::UNAUTHORIZED,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        };
        Response::builder().status(status).body(body).unwrap()
    }
}