-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy patherr.rs
More file actions
65 lines (57 loc) · 1.74 KB
/
err.rs
File metadata and controls
65 lines (57 loc) · 1.74 KB
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
use aide::OperationOutput;
use axum::response::{IntoResponse, Response};
use axum::Json;
use hyper::StatusCode;
use crate::db::DbError;
/// An error type for route handlers.
///
/// The error contains a status code and an optional error message.
#[derive(Debug)]
pub(crate) struct HandlerError(StatusCode, Option<String>);
impl HandlerError {
/// Creates a handler error.
///
/// The input message should start with a lowercase letter.
/// It will be capitalized in the response.
pub(crate) fn new(status_code: StatusCode, msg: Option<&str>) -> Self {
Self(
status_code,
msg.map(|s| {
// capitalize first letter
let mut t = s
.chars()
.next()
.expect("handler error messaged contained empty string")
.to_uppercase()
.to_string();
t.push_str(&s[1..]);
t
}),
)
}
}
impl IntoResponse for HandlerError {
fn into_response(self) -> Response {
(self.0, self.1.unwrap_or_default()).into_response()
}
}
// for Aide
impl OperationOutput for HandlerError {
type Inner = (StatusCode, Json<HandlerError>);
}
impl From<DbError> for HandlerError {
fn from(e: DbError) -> Self {
Self(StatusCode::INTERNAL_SERVER_ERROR, Some(e.to_string()))
}
}
impl From<anyhow::Error> for HandlerError {
fn from(e: anyhow::Error) -> Self {
Self(StatusCode::INTERNAL_SERVER_ERROR, Some(e.to_string()))
}
}
#[cfg(feature = "postgres")]
impl From<tokio_postgres::Error> for HandlerError {
fn from(e: tokio_postgres::Error) -> Self {
Self(StatusCode::INTERNAL_SERVER_ERROR, Some(e.to_string()))
}
}