summaryrefslogtreecommitdiffstats
path: root/src/error.rs
blob: 351c01a9f4391b86e7e2a3dddf5ab23b5efa4752 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use axum::{http::StatusCode, Json};
use serde_json::json;

pub type Result<T, E = Error> = std::result::Result<T, E>;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("IO error: {0}")]
    IO(#[from] std::io::Error),

    #[error("Env variable error: {0}")]
    Env(#[from] dotenvy::Error),

    #[error("Axum error: {0}")]
    Axum(#[from] axum::Error),

    #[error("Http error: {0}")]
    Http(#[from] axum::http::Error),

    #[error("Json error: {0}")]
    Json(#[from] serde_json::Error),

    #[error("Database error: {0}")]
    Sqlx(#[from] sqlx::Error),

    #[error("Migration error: {0}")]
    Migration(#[from] sqlx::migrate::MigrateError),

    #[error("Failed to hash password: {0}")]
    PasswordHash(#[from] argon2::password_hash::Error),

    #[error("User not found")]
    UserNotFound,

    #[error("User with that email already exists")]
    EmailExists,

    #[error("Invalid email: {0}")]
    EmailInvalid(#[from] email_address::Error),

    #[error("Invalid email or password")]
    LoginInvalid,

    #[error("{0}")]
    Other(String),
}

impl From<&Error> for StatusCode {
    fn from(value: &Error) -> Self {
        match value {
            Error::UserNotFound => StatusCode::NOT_FOUND,
            Error::EmailExists => StatusCode::CONFLICT,
            Error::EmailInvalid(_) => StatusCode::UNPROCESSABLE_ENTITY,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl axum::response::IntoResponse for Error {
    fn into_response(self) -> axum::response::Response {
        // TODO: implement [rfc7807](https://www.rfc-editor.org/rfc/rfc7807.html)

        Json(json!({
            "status": StatusCode::from(&self).to_string(),
            "detail": self.to_string(),
        }))
        .into_response()
    }
}