summaryrefslogtreecommitdiff
path: root/src/error.rs
blob: 4f1bedd55247b575f0acd6800941d9ee8a510400 (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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use crate::auth::Error as AuthError;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde_json::json;
use std::io;
use tracing::error;

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("generic error")]
    Generic,

    #[error("auth: {source}")]
    Auth {
        #[from]
        source: AuthError,
    },

    #[error("db: {source}")]
    Db {
        #[from]
        source: sqlx::Error,
    },

    #[error("buffer parse: {source}")]
    ParseInt {
        #[from]
        source: std::num::ParseIntError,
    },

    #[error("io: {source}")]
    Io {
        #[from]
        source: io::Error,
    },
}

impl IntoResponse for Error {
    fn into_response(self) -> Response {
        error!("{}", self.to_string());
        let (status, error_message) = match self {
            Self::Auth { source } => source.get(),
            Self::Generic => (StatusCode::INTERNAL_SERVER_ERROR, ""),
            Self::Db { source } => {
                error!("{source}");
                (StatusCode::INTERNAL_SERVER_ERROR, "Server Error")
            }
            Self::Io { source } => {
                error!("{source}");
                (StatusCode::INTERNAL_SERVER_ERROR, "Server Error")
            }
            Self::ParseInt { source } => {
                error!("{source}");
                (StatusCode::INTERNAL_SERVER_ERROR, "Server Error")
            }
        };
        let body = Json(json!({
            "error": error_message,
        }));
        (status, body).into_response()
    }
}