summaryrefslogtreecommitdiff
path: root/src/error.rs
blob: 6bc4fc509cb54fb7b6b736b696e336187f262c82 (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use axum::{
    Json,
    extract::rejection::{JsonRejection, PathRejection, QueryRejection},
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;

pub enum AppError {
    BadRequest(&'static str),
    Conflict,
    Csv(csv::Error),
    Database(sqlx::Error),
    MethodNotAllowed,
    NotFound,
    Rejection(StatusCode, String),
}

impl From<sqlx::Error> for AppError {
    fn from(e: sqlx::Error) -> Self {
        match e {
            sqlx::Error::Database(e) if e.is_unique_violation() => AppError::Conflict,
            sqlx::Error::RowNotFound => AppError::NotFound,
            e => AppError::Database(e),
        }
    }
}

impl From<csv::Error> for AppError {
    fn from(e: csv::Error) -> Self {
        AppError::Csv(e)
    }
}

impl From<JsonRejection> for AppError {
    fn from(rejection: JsonRejection) -> Self {
        AppError::Rejection(rejection.status(), rejection.body_text())
    }
}

impl From<QueryRejection> for AppError {
    fn from(rejection: QueryRejection) -> Self {
        AppError::Rejection(rejection.status(), rejection.body_text())
    }
}

impl From<PathRejection> for AppError {
    fn from(rejection: PathRejection) -> Self {
        AppError::Rejection(rejection.status(), rejection.body_text())
    }
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::BadRequest(message) => (StatusCode::BAD_REQUEST, message.to_owned()),
            AppError::Conflict => (StatusCode::CONFLICT, "already exists".to_owned()),
            AppError::Csv(e) => {
                tracing::error!("csv error: {e}");
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "internal server error".to_owned(),
                )
            }
            AppError::Database(e) => {
                tracing::error!("database error: {e}");
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "internal server error".to_owned(),
                )
            }
            AppError::MethodNotAllowed => (
                StatusCode::METHOD_NOT_ALLOWED,
                "method not allowed".to_owned(),
            ),
            AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_owned()),
            AppError::Rejection(status, message) => (status, message),
        };
        if status.is_client_error() {
            tracing::debug!(%status, error = %message, "request failed");
        }
        (status, Json(json!({ "error": message }))).into_response()
    }
}