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
|
use axum::{
Json,
extract::rejection::{JsonRejection, PathRejection, QueryRejection},
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
pub enum AppError {
BadRequest(&'static str),
Conflict,
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<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::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),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
|