-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp_types.rs
49 lines (42 loc) · 1004 Bytes
/
app_types.rs
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::{
extract::FromRequest,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Serialize;
pub type AppResult<T> = Result<AppJson<T>, AppError>;
#[derive(FromRequest)]
#[from_request(via(axum::Json), rejection(AppError))]
pub struct AppJson<T>(pub T);
impl<T> IntoResponse for AppJson<T>
where
axum::Json<T>: IntoResponse,
{
fn into_response(self) -> Response {
axum::Json(self.0).into_response()
}
}
pub struct AppError(pub anyhow::Error);
impl IntoResponse for AppError {
fn into_response(self) -> Response {
#[derive(Serialize)]
struct ErrorResponse {
message: String,
}
(
StatusCode::INTERNAL_SERVER_ERROR,
AppJson(ErrorResponse {
message: self.0.to_string(),
}),
)
.into_response()
}
}
impl<E> From<E> for AppError
where
E: Into<anyhow::Error>,
{
fn from(err: E) -> Self {
Self(err.into())
}
}