soph_server/response/
error.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
50
51
52
53
54
55
56
57
58
59
60
61
use crate::error::Error;
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
};

impl IntoResponse for Error {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            #[cfg(feature = "request-auth")]
            Self::Auth(error) => (StatusCode::UNAUTHORIZED, error.to_string()),
            #[cfg(feature = "request-form")]
            Self::FormRejection(error) => (StatusCode::BAD_REQUEST, error.to_string()),
            #[cfg(feature = "request-path")]
            Self::PathRejection(error) => (StatusCode::BAD_REQUEST, error.to_string()),
            #[cfg(feature = "request-query")]
            Self::QueryRejection(error) => (StatusCode::BAD_REQUEST, error.to_string()),
            #[cfg(feature = "request-json")]
            Self::JsonRejection(error) => (StatusCode::BAD_REQUEST, error.to_string()),
            #[cfg(feature = "request-multipart")]
            Self::MultipartRejection(error) => (StatusCode::BAD_REQUEST, error.to_string()),
            #[cfg(feature = "request-multipart")]
            Self::Multipart(error) => (StatusCode::BAD_REQUEST, error.to_string()),
            #[cfg(feature = "request-validate")]
            Self::Validate(error) => (
                StatusCode::BAD_REQUEST,
                format!("Validation error: {}", error),
            ),
            #[cfg(feature = "database")]
            Self::SeaOrm(error) => {
                let status = match error {
                    sea_orm::DbErr::RecordNotFound(_) => StatusCode::NOT_FOUND,
                    _ => StatusCode::INTERNAL_SERVER_ERROR,
                };

                (status, error.to_string())
            }
            #[cfg(feature = "response-view")]
            Self::Tera(error) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("View error: {error}"),
            ),
            _ => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
        };

        tracing::warn!(error = message, "response");

        #[cfg(not(feature = "response-json"))]
        {
            (status, message).into_response()
        }

        #[cfg(feature = "response-json")]
        {
            crate::response::json()
                .code(status)
                .message(message)
                .into_response()
        }
    }
}