summaryrefslogtreecommitdiff
path: root/src/routes/errors.rs
blob: 5161e9a0f89454c1174462416eaca24fc9aeb9a3 (plain)
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
40
41
42
use axum::{Json, body::Body, http::{Response, StatusCode}, response::IntoResponse};
use serde_json::{json};

pub enum RouteError {
    Internal(String),
    MalformedField(String),
    UserCreateEmailExists(String),
    UserCreateUsernameExists(String),
    UnregisteredEmail(String),
    AuthorizationFailure(),
    NotFound(String),
}

impl IntoResponse for RouteError {
    fn into_response(self) -> Response<Body> {
        let (status, message) = match self {
            Self::Internal(message) => {
                (StatusCode::INTERNAL_SERVER_ERROR, message)
            },
            RouteError::UserCreateEmailExists(email) => {
                (StatusCode::BAD_REQUEST, format!("user with email \"{}\" already exists", email))
            },
            RouteError::UserCreateUsernameExists(username) => {
                (StatusCode::BAD_REQUEST, format!("user with username \"{}\" already exists", username))
            },
            RouteError::UnregisteredEmail(email) => {
                (StatusCode::BAD_REQUEST, format!("email \"{}\" is not registered", email))
            },
            RouteError::AuthorizationFailure() => {
                (StatusCode::UNAUTHORIZED, format!("failed to authorize"))
            },
            RouteError::NotFound(resource) => {
                (StatusCode::NOT_FOUND, format!("{resource} not found"))
            },
            RouteError::MalformedField(field) => {
                (StatusCode::BAD_REQUEST, format!("malformed {field}"))
            }
        };

        (status, Json(json!({"error": message}))).into_response()
    }
}