summaryrefslogtreecommitdiff
path: root/server/src/errors.rs
blob: 304d7446d61e67b7bcb4c010e6e96e77e01f20fa (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
43
44
45
46
47
48
49
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde_json::json;

pub enum AppError {
    Generic,
    Database,
    BadRequest(String),
    NotFound,
    TokenCreation,
    InvalidToken,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, error_message) = match self {
            AppError::Generic => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Generic error, can't find why".to_string(),
            ),
            AppError::Database => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Error with database connection".to_string(),
            ),
            AppError::BadRequest(value) => (StatusCode::BAD_REQUEST, value),
            AppError::NotFound => (StatusCode::NOT_FOUND, "Element not found".to_string()),
            AppError::TokenCreation => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Token creation error".to_string(),
            ),
            AppError::InvalidToken => (StatusCode::BAD_REQUEST, "Invalid token".to_string()),
        };

        let body = Json(json!({
            "error": error_message,
        }));

        (status, body).into_response()
    }
}

impl From<sqlx::Error> for AppError {
    fn from(_error: sqlx::Error) -> AppError {
        AppError::Database
    }
}